Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have a "var" as a Global variable [closed]

Tags:

c#

I have noticed there are other threads on global variables in c#. Such as integers, strings etc. e.g.

public static int;

But I need to use a "var" which the other thread don't mention and

public static var;

doesn't seem to work.

So what I'm asking is it possible to have a "var" as a global variable in c#?

like image 705
difurious Avatar asked Jan 28 '13 22:01

difurious


2 Answers

C# specification (section 26.1) reads:

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

It goes further:

A local variable declarator in an implicitly typed local variable declaration is subject to the following restrictions:

  • The declarator must include an initializer.
  • The initializer must be an expression.
  • The initializer expression must have a compile-time type which cannot be the null type.
  • The local variable declaration cannot include multiple declarators.
  • The initializer cannot refer to the declared variable itself

So no, you cannot do this. Moreover I would recommend steering away from even thinking about global variables.

Global variables are not supported by the language. You may find alternatives in public static fields, but this will leak object state and break encapsulation.

like image 186
oleksii Avatar answered Nov 14 '22 22:11

oleksii


No, because var is not a type itself, it merely takes on the form of whatever expression is on the righthand side of the assignment:

var num = 1;

is the same as:

int num = 1;

when declaring variables that are scoped outside of a method, you need to use the full type designator:

public static int num = 1;

or

public static int Num {get;set;}

etc

like image 28
mellodev Avatar answered Nov 15 '22 00:11

mellodev