var in class gives error

Pratik picture Pratik · Dec 21, 2010 · Viewed 17.9k times · Source

Possible Duplicate:
Using var outside of a method

class A {
string X;
}
// Proper
class A {
var X;
}
// Improper (gives error)

Why is it, that i cant have var type variable declare in Class and what can be done in order to achieve it OR what is an alternative ?

In function/method, i can declare a var type variable,then why can't, i do it in class ?

Thanks.

Answer

Marc Gravell picture Marc Gravell · Dec 21, 2010
// method variable
var X;

is never valid - even inside a method; you need immediate initialization to infer the type:

// method variable
var X = "abc"; // now a string

As for why this isn't available for fields with a field-initializer: simply, the spec says so. Now why the spec says so is another debate... I could check the annotated spec, but my suspicion would be simply that they are more necessary for method variables, where the logic is more complex (re LINQ etc). Also, they are often used with anonymous types (that being the necessity for their existence); but anonymous types can't be exposed on a public api... so you could have the very confusing:

private var foo = new { x = 123, y = "abc"}; // valid
public var bar = new { x = 123, y = "abc"}; // invalid

So all in all I'm happy with the current logic.