Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using var outside of a method

Tags:

c#

.net

var

I wanted to use the var keyword to declare a field in my class however var only seems to work inside methods.

The code I have looks like:

public static Dictionary<string, string> CommandList = new Dictionary<string, string>{};

and I wanted to have:

public static var CommandList = new Dictionary<string, string>

How come this isn't possible?

like image 556
Jamie Dixon Avatar asked Dec 18 '09 16:12

Jamie Dixon


People also ask

Can var be used outside a function?

Variables declared Globally (outside any function) have Global Scope. Global variables can be accessed from anywhere in a JavaScript program. Variables declared with var , let and const are quite similar when declared outside a block.

How do you use a variable outside a method in Java?

The variables that are defined inside a method are local to that method, so you cannot use them outside. If you want to use them outside, define instance variables in the beginning of your class.

How do you use a variable within a method which is defined outside the method?

Variable defined inside the method: The variables that are defined inside the methods can be accessed within that method only by simply using the variable name. Example – var_name. If you want to use that variable outside the method or class, you have to declared that variable as a global. def access_method( self ):

Can we declare variable outside main method?

Static variables in methods The variables with in a method are local variables and their scope lies within the method and they get destroyed after the method execution. i.e. you cannot use a local variable outside the current method which contradicts with the definition of class/static variable.


1 Answers

My article on the subject:

Why no var on fields?

To summarize:

  1. If we have "var" fields then the type of the field cannot be determined until the expression is analyzed, and that happens after we already need to know the type of the field.

  2. What if there are long chains, or even cycles in those references? All of those algorithms would have to be rewritten and tested in a world where top-level type information is being determined from them rather than being consumed by them.

  3. If you have "var" fields then the initializer could be of anonymous type. Suppose the field is public. There is not yet any standard in the CLR or the CLS about what the right way to expose a field of anonymous type is.

like image 98
Eric Lippert Avatar answered Oct 10 '22 07:10

Eric Lippert