Is it possible to have "var" as a global variable

I noticed that there are other streams of global variables in C #. Such as integers, strings, etc., for example,

public static int; 

But I need to use "var", which is not mentioned in another thread, and

 public static var; 

doesn't seem to work.

So I ask, is it possible to have "var" as a global variable in C #?

+6
source share
2 answers

The C # specification (section 26.1) states:

[`var is] an implicitly typed declaration of a local variable ...

Further:

The local variable declarator in an implicitly typed local variable declaration extends to the following restrictions:

  • The declarator must include an initializer.
  • The initializer must be an expression.
  • The initializer must have a compile time type, which cannot be a null type.
  • A local variable declaration cannot include multiple declarators.
  • The initializer cannot reference the declared variable

No, you cannot do this. Moreover, I would recommend avoiding even thinking about global variables.

Global variables are not supported by the language. You can find alternatives in the public static fields, but this will lead to a leak of the state of the object and violation of encapsulation.

+6
source

No, since var is not the type itself, it just takes the form of any expression on the right side of the assignment:

 var num = 1; 

matches with:

 int num = 1; 

when declaring variables that are restricted outside the method, you need to use a full type pointer:

 public static int num = 1; 

or

 public static int Num {get;set;} 

etc.

+6
source

All Articles