Why can't class fields be var? [duplicate]
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?
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.
The var
keyword was designed for anonymous types, which can only be used inside of a method.
Also, you're wrong; the compiler cannot always deduce a var
field.
What happens if you compile the following:
class A {
public readonly var value = B.value;
}
class B {
public readonly var value = B.value;
}
This situation is impossible to recreate with local variables, since a variable cannot be referenced before it's defined.
The general problem here is that you're asking the compiler to consume type information while it's still generating that information.
Eric Lippert explains in greater depth.
I see two reasons:
- It might be desirable to make the declaration of types in a public interface explicit
- It's hard to implement. The C# compiler compiles in multiple phases.
At first it parses everything apart from method bodies so it knows about everything outside of function bodies. Then it can use that information to compile method bodies individually. What happens while compiling one method body hasn't much effect on what happens when compiling other method bodies.
If you could usevar
for fields the expression body of the field initializer would affect the type of the field and thus many other methods. So it doesn't fit the compiler design well.
This is a guess, but initialization of class-level fields must be done as part of the initialization (constructor) process for a Type, whereas initialization of a method-level variable happens when the method's stack frame is constructed. Perhaps the distinction is related to how these processes are compiled (how their implementation is created) inside the framework.
精彩评论