using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace LearnThread
{
class Delay
{
public int timePass()
{
static int i=0;
for(i=0; i<100;i++)
{
Thread.Sleep(1000);
}
return i;
}
}
}
Error:The modifier ‘static’ is not valid for this item
Why static is error here? We cannot use static for int as we can use in C language?
You can’t declare a locally scoped variable as
static, which is what you are doing.You can create a static field or static property for a class (i.e. it is a member of a class), which would reside outside of a method.
Though, this code seems kinda dumb… why bother using a static field in a for-loop iteration? It can cause a lot of issues with multiple calls to the method. I presume that you’re either learning C# by playing around with crazy code, or you are trying to solve another problem and threw this code in. Either that or…. you’re doing it wrong. 🙂