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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With