C#3.0 introduces the new keyword Var, which is a type that can be used to declare local variables.
Code
var I = 1; //int类型
var j = ”reallypride”; //string类型
var k = new[] { 1, 2, 3, 4 }; //int[]类型
var x; //错误,必须初始化
var y = null; //错误,不可以为空
Use the var variable essentials:
1. Using Var to declare a local variable, the compiler automatically infers the type of the variable based on the subsequent initialization expression, which is a strongly typed type.
A 2.var variable must be initialized when declared, cannot be empty, and its type can be inferred at compile time. Variables can only hold this type after initialization.
3. Arrays can also be used as VAR types.
Anonymous type
Anonymous types allow you to define inline types, and you do not have to display a declaration type. often used with Var. Such as
Code
var p1 = new { name = ”reallypride”, age = 23 };
var p2 = new { name = “jingxuan”, age = 23 };
The compiler automatically defines a class that contains the name and age attributes. P1 is the same as the P2 structure and is an instance of the same class. Let's define a variable:
Code
var p3 = new { age = 23, name = “reallypride” };
The compiler creates a new class, that is, P3 and P1,P2 are not instances of the same class because the P3 declares the properties differently.
{} is an anonymous initializer.
If you want to define an array, you can define this:
Code
var intArray = new[] { 1, 2, 3, 4 };
var strArray = new[] { “a”, “b”, “c” };
var someTypeArray = new[] { new { name = “reallypride”, age = 23 }, new { name = “jingxuan”, age = 23 } };
Anonymous type essentials:
1. You can use the New keyword to invoke the anonymous initializer to create an anonymous type.
2. Anonymous type inherits directly from System.Object.
3. An anonymous type of property is the compiler's automatic inference based on the initializer.
Some might think that with the keyword VAR, other types of keywords become redundant.
In fact, VAR is simplifying our programming so that we don't have to write two of its types because we define a variable.
If you define an instance of a user class, the previous method is defined as this:
Code
User user=new User();
And now we can define this:
Code
var user=new User();
We can spend more time on the implementation of the software function rather than on the code.