开发者

Question on the scope of using the keyword "Var"

New to C# I have done a good bit of reading on learning the language and in the 2 full books and numerous site articles, do I ever recall reading about the keyword "var" usage not allowed within the class scope but needing to be within some nested element of the class (i.e. method). I know you can declare the variable with an access modifier and type (i.e. string,开发者_如何学运维 int..etc.).

Even this site I can find question on using "var" but not regarding its limitation.

Maybe it is so obvious to every other individual that most writers does not make mention of this and I am the last reader on earth it isn't obvious to - would someone be so kind to explain the reason behind this?

NOT ALLOWED EXAMPLE

public class SomeClass
{
    var SomeVariable = new SomeClass();
}

ALLOWED EXAMPLE

public class SomeClass
{
   public void SomeMethod()
   {
      var SomeVariable = new SomeClass();
   }
}

I can obviously declare

public class SomeClass
{
  public string SomeVariable;
}


You're allowed to use var for local declarations, but not fields, basically.

Eric Lippert's blog post explains why. Essentially:

  • It introduces some awkward situations where there's ambiguity
  • It means working out a way of exposing anonymous types as part of a class's public interface, potentially
  • It doesn't work well with the way the compiler is implemented (which may sound like the team is just lazy, but they need to prioritise work like anyone else)

(I certainly hope neither of your C# books was C# in Depth, 'cos I definitely mention it there... section 8.2.2 in both editions :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜