Is there any reason behind this kind of implementation, why I am not able to declare
class Defaultclass
{
static void Main(string[] args)
{
static int x=5;
}
}
throws compilation error
Is there any reason behind this kind of implementation, why I am not able to declare
class Defaultclass
{
static void Main(string[] args)
{
static int x=5;
}
}
throws compilation error
It may make sense in C++, but in C# the designers apparently thought it wasn't particularly worth putting in the language.
For a similar effect, you can just move the declaration to the class scope. (It will be accessible from all methods of the class, not just the one you wanted, though.)
class Defaultclass
{
static int x = 5;
static void Main(string[] args)
{
}
}
It is because static variable shared the value of it among all instances of the class.
Now what you are doing is, you are defining a variable in the function. The function level variables are compiled and executed at Function level. Thus static cannot be declared at function level.
I don't know what you are trying to do but you can use const or readonly. However, it cannot replace what static meant to be.
So coming back to the point of static variable within the function. This is how it id defined at compile language level.