2

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

1
  • because it doesn't make sense Commented Sep 13, 2014 at 8:30

2 Answers 2

2

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)
    {
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.