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