An explanation of anonymous objects and VAR and dynamic types in C #

Source: Internet
Author: User
With the development of C #, the content of the language continues to enrich, development becomes more convenient and fast, C # 's sharpness is undoubtedly obvious. C # language from birth is a strong type of language, this nature has not changed today, I think the future will not change. Since it is a strongly typed language, writing any program requires that the following basic conditions be met:





1. Variable declaration must indicate its type



2. After the variable type is clear, its type cannot be changed at runtime.



The code is as follows:


    Public  class Student    {public            string Name {get; set;}            public int Age {get; set;}            public string like {get; set;}    }public class Student
     {
     public string Name {get; set;}
     public int Age {get; set;}
     public string Like {get; set;}
     }
static void Main (string [] args)
{int a = 10; string s = "abc";
     Student student = new Student (); // A compilation error occurs below, and the variable type cannot be changed after being declared
     s = a;
     student = s;
     a = 10.1f;
} 


However, in the actual development we often face the following several common problems:



1, in a larger program, only one or a few (not more than 3) need to use some or some type (such as Student), other places no longer need these types. Declaring a single student type, the required amount of code, may exceed the amount of code used when using that type, and the input-output ratio is not cost-effective.



2. In a program, only some properties or methods of some type of object are required to participate in the operation. In this case, the object of the type object is temporarily converted to some of the properties and methods required by the program, which makes the program more streamlined.



3. Other circumstances ..... I haven't noticed ... Welcome to add ...



The above common problems in real-world C # Development have a better solution in JAVASCRIPT development, as follows:


// Here you need to simulate a student object in js
student = {"name": "Zhang San", "age": 20, "like": "LOL"};
// In this js, a teacher object needs to be simulated
teacher = {"name": "Mr. Li", "like": "Confiscation of student's mobile phone, own LOL"};
// Here you need to convert the student student into an object with only name and age
person = {"name": student.name, "age": student.age};


If you are not familiar with the above JS syntax, you can go to Baidu search "JSON grammar", tell you very simple oh (and very important).



Anonymous object (anonymous type)



So C # has absorbed this syntactic advantage of the JavaScript scripting language in version 3.0, upgrading C # to support this syntactic form (C # remains strongly typed ). The sample code is as follows:


static void Main(string[] args)
{     new {Name="Zhang San",Age=20,Like="LOL"};
}


The C # code above tells the compiler to create an object with the Name,age,like three properties, which is the value corresponding to the property after the new keyword. So we avoided the "create an object first to have the constraint of that object type", so in the development process for using fewer types we no longer have to create a separate class, the above mentioned problem 1 is resolved .



The object that is created now does not specify a specific type, so it is called an anonymous object .



VAR debut



Now to use an anonymous object, you need to reference it using a variable. Although we did not specify the type of the object at the time of creation, the compiler helped us create a type with related properties and methods during the compilation process. The type names that are compiled at this time are randomly generated, so the variable type cannot be determined. Examples are as follows:


static void Main (string [] args)
{// XXX is a type declaration // x is a reference variable
      XXX x = new {Name = "Zhang San", Age = 20, Like = "LOL"};
} 


Although we don't know the compiler-generated type name, we can let the compiler infer the variable type based on the result of the compilation itself. the var keyword now works:


static void Main(string[] args)
{     var x = new {Name="Zhang San",Age=20,Like="LOL"};
}


The var keyword indicates that the type of X is determined (presumed) by the value assigned to it, and can be given smart hints based on the compiler's presumption, such as:






var usage precautions:



1. var can only declare local variables within the method



2, var declaration of the variable after being assigned to the type is determined, the subsequent program can not be assigned to other types of values



3, var x = new Object () there is no meaning, do not write such code ....






Now that there is support for anonymous objects and VAR inference types, we can handle the above mentioned problem 2. The sample code is as follows:


     static void Main(string[] args)
        {            
        var x = new { Name = "Zhang San", Age = 20, Like = "LOL" };            
        var s = new { Name = x.Name, Age = x.Age };  
        }


For example only, if you are familiar with LINQ or the entity Framework, the usage of question 2 will be overwhelming ....



Dynamic Type Dynamics Appearances



The use of anonymous types is generally limited to the local method, which can be understood as : With the definition, the use of the end disappears. What should I do if I have the following conditions?





  static void Main(string[] args)
        {            
        var x = GetObject(); 
        }        
        private static XXX GetObject()
        {            
        return new { Name = "Zhang San", Age = 20, Like = "LOL" };
        }

An anonymous object is returned by the GetObject method, so the method return value type name cannot be determined, and XXX is temporarily replaced here. In this case the returned type is indeterminate and can be indicated by using dynamic. As follows:


          Main (x =    {Name =, age =, like =


The method does not have a syntax error at this point, and the program compiles and executes successfully. So what does dynamic do to make the above program compile successfully?



The role of dynamic:



1 dynamic type, dynamic type meaning is program writing, compile stage type is not deterministic, at runtime and then through the reflection mechanism to determine the properties of related objects or methods. Therefore, the authoring phase does not perform syntax detection.



2. Dynamic can be used to declare fields, properties, method parameters, method return values



3. Dynamic does not support smart hints because what dynamic is not known when you write code (reflection)



A variable declared by dynamic, which can be understood as an object type variable. So assigning any type value to a dynamic variable is correct, but when a variable is used to get a property value or a method is called (at which point the program is definitely in runtime), the CLR checks (reflects) whether the property or method being called exists and does not have a report run-time exception.



Dynamic is used everywhere in ASP. NET MVC Web development, although it looks complex, essentially what is said above.



Description



var and dynamic seem to function similarly, but they are different:


var dynamic
Declaration field x Yes
Local Variables yes
method parameter type x Yes
method return value type x
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.