Using var outside of a method

后端 未结 3 1601
遇见更好的自我
遇见更好的自我 2020-12-03 20:56

I wanted to use the var keyword to declare a field in my class however var only seems to work inside methods.

The code I have looks like:

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-03 21:49

    From the C# reference

    • Beginning in Visual C# 3.0, variables that are declared at method scope can have an implicit type var.

    Also from The C# Programming Reference

    • var can only be used when a local variable is declared and initialized in the same statement; the variable cannot be initialized to null, or to a method group or an anonymous function.
    • var cannot be used on fields at class scope.

    It just isn't intended for the usage you have in mind.

    It's primary aim is to allow the support of anonymous types in your code, with the added advantage of allowing a nice terse way of specifying local variables.

提交回复
热议问题