1. Why use inferred type var
var can automatically infer the local variable type based on the initial value of the variable, and can use Var when it is not possible to determine the specific type of the variable used
2. How to use inferred type var
Client code
Static voidMain (string[] args) { varA =Ten; varClassName ="Learning from Var"; //var student = new Student{studentname = "Wang Hua", age = +};//Creating Objects varStudent =New{Studentname ="Simon", age = -};//Anonymous ClassConsole.WriteLine ("{0} personally in {1}, where {2}, {3} years old, mastered the best! ", A, className, student. Studentname, student. Age); Console.ReadLine (); }
Sudent class definition
Public class Student { publicstringgetset;} Public int Get Set ;} Public int Get Set ;} }
Output
This shows that Var can infer the type of a variable based on the value of the variable
Note: Anonymous classes: Anonymous classes do not need to write classes and their members in advance, and only add properties cannot add methods, anonymous classes are not nameless, but the compiler generates class names in the background
3. Questions to note when using inferred type var
(1) variables using var must be local variables, member variables cannot be modified with Var
(2) When using VAR, the variable must be initialized at the same time and cannot be empty
(3) var itself does not define a new type
4. The difference between Var and object
var is similar to object, but there are some differences in that Var cannot be assigned another type of assignment after inferring the type of the variable, and object does not have this limitation
Static void Main (string[] args) { objectten; " should be right. " ; var Ten ; " Are you wrong? "; }
The former a compile no problem, the latter B has a problem, so you can see the difference between Var and object
Inferred type var