Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't class fields be var? [duplicate]

Tags:

c#

class A {     A()     {         var x = 5;   // this is allowed     }      var _x = 5;   // the compiler is unhappy } 

I guess the compiler must be able to deduce the type for the member variable just the same way it does it for the local one. So what's the difference?

like image 392
armen Avatar asked Dec 16 '10 14:12

armen


People also ask

Can you use VAR in class?

var can only be used when a local variable is declared and initialized in the same statement; the variable cannot be initialized to null, or to a method group or an anonymous function. var cannot be used on fields at class scope.

Can we use VAR in class level in C#?

In C#, when we declare a variable inside a class, the variable can be accessed within the class. This is known as class level variable scope.


1 Answers

Eric Lippert answered your question right here: Why no var on fields?

Basically, for the general case it would require re-writing the C# compiler, as the way it currently does type inference would not work for cycles of var field variable assignments.

like image 187
thecoop Avatar answered Oct 04 '22 06:10

thecoop