The difference between Var, object, and dynamic and its use (reprint)

Source: Internet
Author: User
Tags new set

var,Object, the difference between the dynamic and the use of the reading directory: I. Why are they three two. The reason to be able to assign any value three. Use of dynamic Four. Considerations for using dynamic compare these three reasons because they are very similar in use. You can assign any type of value to a variable that they declare. Take a look at the following example:varA =1;Objectb =1;d ynamic C=1in the above example, it looks like the three are very similar, but the rationale behind them is very different. var is introduced in C # 3, but it's just a syntax. var is not a type in itself, and the other object and dynamic are types. The variable declared by Var at the moment of assignment determines what type it is. So if you use this, there will be a compile error:varA =1; a="Test"The reason that object can be assigned to any type is known because all types are derived from object. So it can be assigned to any type:ObjectA =1; a="Test";d ynamic not determine the actual type at compile time, but at run time. So the following code is able to compile, but will be in the Run Times error: Dynamic a="Test"; a++; iii. use of dynamic1using this type directly, you can easily insert properties, method dynamic person=NewSystem.Dynamic.ExpandoObject ();p erson.id=1;p Erson.title="Your source network";p Erson.url="gzmsg.com";p erson.co="Software Development";p erson.des=Newfunc<string> (() = Person.title +Person.url); Response.Write (Person.des ());//Result: Your source network gzmsg.com2Enumerate all Membersforeach(varPropertyinch(Idictionary<string, object>) {Response.Write (property. Key+": "+Property . Value);//results: id:1title: Source network Url:gzmsg.comco: Software developmentDes:System.Func '1[System.String]}3Examples of processing reflections commonly used to simplify reflection:ObjectCalc =Getcalculator (); Type Calctype=Calc. GetType ();Objectres = Calctype.invokemember ("ADD", BindingFlags.InvokeMethod,NULL,New Object[] {Ten, - });intsum =Convert.ToInt32 (res); After using the dynamic: Dynamic calc=getcalculator ();intsum = Calc. ADD (Ten, -); Four, the note of using dynamic has dynamic,.net and the advantage of dynamic type, but because all operations of the dynamic type are determined at runtime, all errors cannot occur at compile time, and need to be taken very carefully when used. Because dynamic is a type, if a function accepts a parameter that determines the type, it cannot pass in the dynamic type, and there is a compilation error. Example: Copy code Public intADD (intAintb) {returnA +b;} Dynamic Test1=1;d ynamic test2=2; ADD (Test1, test2);

Also, it is best not to use the dynamic type as a function when we write the function ourselves.

parameter, which is like using object as a function parameter, will be the dimension of the program

The following troubles.

No one can determine what the user is passing in, and there is no problem with the compile time

。 If an error occurs at run time, it can be a disaster.

1. var means "The type of the variable is determined at compile time", Var lets you enter a few words when initializing the variable, the compiler will infer the variable type according to the right value, Var can only be used for the definition of the local variable, you can not define the property of the class as Var, You cannot define a method's return value type or a parameter type as Var

2. Dynamic means that "the type of the variable is determined at run time", and the Dynamics language runtime DLR is a new set of APIs in the. NET Framework 4 Beta 1 that provides the C # In the dynamic type of support, dynamic tells the compiler, simply ignore what type, run-time inference not later, the dynamic type does not skip the type check, but deferred to the runtime. If a type incompatibility is detected at run time, an exception is thrown. Variables, properties, method return value types, and parameter types can all be defined as dynamic.

You may use dynamic in the following situations:

1.COM objects

2. Dynamic languages (such as Ironpython,ironruby, etc.) objects

3. Reflective objects

Dynamically created objects in 4.c# 4.0

Therefore, dynamic and Var have different meanings.

1.var declaring a local variable is simply a simplified syntax that requires the compiler to infer a specific data type based on an expression.

2.var can only be used to declare local variables inside a method, while dynamic is available for local variables, fields, and parameters.

3. Expressions cannot be converted to Var, but can be transformed into dynamic.

4. A variable declared with Var must be explicitly initialized, but it is not necessary to initialize a variable declared with Dynam.

Often people will take the keyword Var to compare with the dynamic. In fact, var and dynamic are completely two concepts that should not be compared at all. var is actually the "syntactic sugar" that is thrown at compile time, and once compiled, the compile time automatically matches the actual type of the Var variable, and replaces the declaration of the variable with the actual type, which looks as if we were using the actual type to declare when we coded it. When dynamic is compiled, it is actually an object type, except that the compiler makes special processing of the dynamic type so that it does not perform any type checking during compilation, but instead puts type checking into the runtime.

This can be seen from the editor window of Visual Studio. Variables declared with VAR support IntelliSense because visual Studion can infer the actual type of the Var type, whereas a variable declared with dynamic does not support IntelliSense because the compiler knows nothing about the type of its run time. Using IntelliSense for dynamic variables prompts that this operation will resolve at run time http://www.cnblogs.com/stone_w/archive/2011/02/17/1957014.html

The difference between Var, object, and dynamic and its use (reprint)

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.