one. magic var
A variable declaration var was added in C# 3.0. This declaration is similar to JavaScript's var, but it is also different.
1. The same point, it can use var to declare any type of local variable.
2. The difference is that it is only responsible for telling the compiler that the variable needs to infer the type of the variable based on the initialization expression, and it can only be a local variable.
two. Similarities
it can be declared
var integer = 10;
var name = "edisundong";
var numbers = new int[] { 1, 2, 3 };
three. Differences
var is just a keyword. It is not a new type in C# 3.0. It is responsible for telling the compiler that the variable needs to infer the type of the variable based on the initialization expression. The above statement is equivalent to
int integer = 10;
string name = "edisundong";
int[] numbers = new int[] { 1, 2, 3 };
three. Note
1. A value must be assigned at the time of declaration, because the declaration depends on the expression on the right side of the assignment number. If there is the following statement:
var integer;
integer = 10;
An Implicitly typed locals must be initialized error will be reported during compilation.
2. After using var to declare a local variable, it still has a strong type and can be tested as follows:
var integer = 10;
integer = "edisundong";
A Cannot implicitly convert type 'string' to 'int' error will be reported during compilation.
3. The compile-time type of the initializer expression cannot be the empty (null) type. The compiler cannot infer the type of local variables based on null, such as the following statement:
var integer = null;
Cannot assign '
4. The initialization statement must be an expression. The initialization expression cannot contain itself, but can be a new expression (ie, anonymous type) containing an object or collection initializer.
For example, you can declare it like this:
var coll = new Hashtable();
5. The declaration of var is limited to local variables and can also be included in foreach, for, and using statements. The following usage is incorrect:
class Program
{
private var i = 10; //Global private variables.
static void Main(string[] args)
{ }
}
The contextual keyword 'var' may only appear within a local variable declaration error will be reported during compilation.
This article comes from the CSDN blog. Please indicate the source when reprinting: http://blog.csdn.net/superyoungchaos/archive/2009/12/23/5060696.aspx