2

Possible Duplicates:
Why class fields cannot be var?
Implicit typing; why just local variables?
var in C# - Why can't it be used as a member variable?

the var type cannot be applied to the member variables. I want to know why?

Community
  • 1
  • 1
user496949
  • 83,087
  • 147
  • 309
  • 426

4 Answers4

4

Eric Lippert has a detailed blog post about this: Why no var on fields?

Summary:

  • Even if it were feasible, it would require major compiler upheaval
  • Determining the type could be very complex in some cases, and end up with some weird situations - what would be exposed for a public variable using an anonymous type?

I'd love it for simple cases, but the balance of "simple" may well be hard to decide in an elegant way which "feels right".

ChrisW
  • 54,973
  • 13
  • 116
  • 224
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • oooo nice blog post, haven't seen it yet, cheers Jon. – Maciek Jan 21 '11 at 08:04
  • The link was 404. For this reason I always like to hyperlink like this, `Eric Lippert has a blog post: [title of blog post](url)` -- never like this, `Eric Lippert has [a blog post](url)` -- so as to reference at least the title of the blog post ... so it's possible to find it again, by Googling for the title, if the URL changes. – ChrisW Nov 28 '20 at 09:42
1

var can only be used in a local scope. The actual type must be inferred by the compiler and it is too hard/impossible to determine the type from a construct like this:

class Person
{
    public var Name {get; set;}
}
Emond
  • 50,210
  • 11
  • 84
  • 115
0

To put it simply :

// code fragment

int Add(int x, int y) { return x + y; }

var x = Add(int x, int y); // the compiler will know that the result of the call will be of type int


class X
{
    var x; // illegal, the compiler has no idea what's the target type of X
}
Maciek
  • 19,435
  • 18
  • 63
  • 87
  • 1
    I dont think this is the scope of the question. Think `class X { var x = 5; }` Now answer this.. – nawfal Jul 04 '12 at 19:02
0

Because it's type is not known. This is related to build order of compiler.

You can also have a look at this topic.

Community
  • 1
  • 1
Pabuc
  • 5,528
  • 7
  • 37
  • 52