Implicit type var in C # -- Detailed Example Analysis
From Visual C #3.0, variables declared in the method range can have implicit type var. Implicit type can replace any type, and its specific type is inferred by the compiler according to the context. Next let me summarize some features of implicit types: 1. the var type is inferred by the compiler based on the initial value type. The specific type is eg: var t = "test"; // var is inferred to be string type var p = new Person (); // It is known that Person is a defined class. After compilation, the code will become: Person p = new Person (); 2. the local variable of the var type must be assigned the initial value eg: var t = 1; // correct, t will be inferred as int type, and the value is 1 var t; // an error is returned: local variables of the implicit type must have been initialized. you cannot assign null to a local variable of the implicit type. For example: var t = null; // error: you cannot assign "<null>" to a local variable of the implicit type. 4. the var type variable must be defined in the method or in the get or set accessors. For example, copy the code public void Test () {var t = "test "; // correct} public string Na Me {get {var p = new Person (); // return p correctly. name ;}} class Program {var t = 1; // error: the context keyword "var" can only appear in the local variable declaration} copy Code 5. var cannot be used as the method parameter. For example: public void Test (var t) {}// error: the context keyword "var" can only appear in the local variable declaration. 6. cannot be regarded as the return value type. For example: public var Test () {}// error: not all code paths return values or: the context keyword "var" can only appear in the local variable declaration. if a variable is declared only once, the type eg: var t = "100"; t = 100; // error is returned: the type "int" cannot be implicitly converted to "string" 8. initialization cannot be an anonymous delegate (also called an anonymous method or an anonymous function) eg: var t = delegate (int I) {re Turn I ;}; // error: the "anonymous method" cannot be assigned to an implicit local variable 9. you can use an anonymous class to initialize eg: var person = new {Age = 18, Name = "Kobe"}; // correct // attributes in the anonymous class must be assigned an initial value, otherwise, var person = new {Age, Name} is reported. // the error message is: "Age" does not exist in the current context. "Name" is different from the object defined by var, it is the same in efficiency as defining variables using a strong type method, because the compiler has deduced the type according to the context before running, so it is more efficient than the object. The use of implicit types is a great tool for programming if it is difficult to determine the types, such as using them to store anonymous or anonymous type sets.