Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

var in class gives error [duplicate]

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.

like image 390
Pratik Avatar asked Dec 21 '10 06:12

Pratik


2 Answers

// 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.

like image 184
Marc Gravell Avatar answered Oct 18 '22 00:10

Marc Gravell


If you really don't know the type of object your instance variable will hold, use object, not var. var doesn't mean "i don't know", it means "infer the type for me" - this is why it can never be used on class members.

like image 42
Bradley Smith Avatar answered Oct 18 '22 00:10

Bradley Smith