views:

99

answers:

2

I know it can't be done since using var can only be done for local variables. I'm just wondering if anyone has a theory why the C# team thought this should be so. e.g. what would be wrong with this:

public class SomeClass
{
    var someString = "hello"; //not cool
    public SomeClass()
    {
        var someOtherString = "hello"; //cool
    }
}

If someString is initialised then it is obviously a string just like someOtherString. Why is there one rule for local variables and another for globals?

+4  A: 

Duplicate, hence CW.

See the posting by Eric Lippert:

Let me give you a quick oversimplification of how the C# compiler works. First we run through every source file and do a "top level only" parse. That is, we identify every namespace, class, struct, enum, interface, and delegate type declaration at all levels of nesting. We parse all field declarations, method declarations, and so on. In fact, we parse everything except method bodies; those, we skip and come back to them later.
[...]
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.

Michael Stum
Excellent. For clarity I'll also add the following key quote from that article: "The field declarations have two parts: the type declaration and the initializer. The type declaration that associates a type with the name of the field is analyzed during the initial top-level analysis [...] But the initialization is actually treated as part of the constructor"
BritishDeveloper
+1  A: 

Its to do with the amount of searching the compiler would have to do resolve the type.

Adrian