What does "var" mean in C#?

Possible Duplicate:
Use of var keyword in C#

In C#, how does keyword " var " work?


It means that the type of the local being declared will be inferred by the compiler:

// This statement:
var foo = "bar";
// Is equivalent to this statement:
string foo = "bar";

Notably, var does not define a variable to be of a dynamic type. So this is NOT legal:

var foo = "bar";
foo = 1; // Compiler error, the foo variable holds strings, not ints

var has only two uses:

  • It requires less typing to declare variables, especially when declaring a variable as a nested generic type.
  • It must be used when storing a reference to an object of an anonymous type, because the type name cannot be known in advance: var foo = new { Bar = "bar" };
  • You cannot use var as the type of anything but locals. So you can't use the keyword var to declare field/property/parameter/return types.


    It means the data type is derived (implied) from the context.

    From http://msdn.microsoft.com/en-us/library/bb383973.aspx

    Beginning in Visual C# 3.0, variables that are declared at method scope can have an implicit type var. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type. The following two declarations of i are functionally equivalent:

    var i = 10; // implicitly typed
    int i = 10; //explicitly typed
    

    var is useful for eliminating keyboard typing and visual noise, eg,

    MyReallyReallyLongClassName x = new MyReallyReallyLongClassName();
    

    becomes

    var x = new MyReallyReallyLongClassName();
    

    but can be overused to the point where readability is sacrificed.


    "var" means the compiler will determine the explicit type of the variable, based on usage. For example,

    var myVar = new Connection();
    

    would give you a variable of type Connection.

    链接地址: http://www.djcxy.com/p/53796.html

    上一篇: 使用什么:var或对象名称类型?

    下一篇: “var”在C#中的含义是什么?