Introduction to Var and dynamic collation in C #

Source: Internet
Author: User
Tags new set

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.

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

Use of Var:

1.var can only be used as a local variable, not as a global variable, static variable

2. The definition must be initialized because the type is inferred at compile time

3. Cannot be null when initializing

4. Cannot be a change type after declaration

5. Compile to confirm type

Use occasions

1. Implicit variables: for example var x=1;var y = "abd";(must be initialized when defined, "var" acts as placeholder, compile-time compiler infers type and replaces "Var")

2. Anonymous class:

var cls = new {name= "James", sex=0,age=18};

var cls2 = new {name= "John", sex=1,age=35};

var cls3 = new {name=123, sex = "male", age = 34}

Cls. GetType () = = Cls2. GetType () = = Cls3. The GetType () result returns TRUE. Because the compiler created only one generic class.

var cls4 = new {sex=1,name= ' admin ', age=24}

Cls. GetType () = = Cls2. GetType () results return false, with names consistent, but inconsistent in order, the compiler creates a new generic class

Note: Anonymous classes cannot have methods

Dynamic is a new feature of FrameWork4.0. The advent of dynamic gives C # The characteristics of a weak language type. The compiler no longer checks the type at compile time, and the default dynamic object at compile time supports any attributes you want. For example, even if you know nothing about the objects returned by the Getdynamicobject method, you can call the code as follows, and the compiler will not error:

dynamic variable is an object variable!

Type ConversionsConversions between instances of the dynamic type and other types of instances are straightforward, and developers can easily switch between dyanmic and non-dynamic behavior. Any instance can be implicitly converted to an instance of the dynamic type, as shown in the following example: Dynamic D1 = 7;dynamic D2 = "A string";d ynamic d3 = system.datetime.today;dynamic D4 = syste M.diagnostics.process.getprocesses (); Conversely, an implicit conversion can is dynamically applied to any expression of type dynamic. Or vice versa, any expressions of type dynamic can also be implicitly Convert to a different type. int i = d1;string str = d2;datetime dt = d3; system.diagnostics.process[] procs = D4; overload problem with dynamic type parameter in methodIf you call a method that passes an object of type dynamic, or if the object being called is of type dynamic, then the overload is judged to occur at runtime rather than at compile time. The dynamic Language runtime (Dynamic Language runtime DLR) is a new set of APIs in the. NET Framework 4 Beta 1 that provides support for the type of dynamics in C #. Dynamic programming languages like IronPython and IronRuby are also implemented.

dynamic can simplify reflection .

public class TestClass ()

{

public string Name{get;set;}

public int Add (int a,int b) {return a+b;}

}

Reflection:

var asm = assembly.loadfile (@ "C:/test.dll");

var type =asm . GetType ("TestClass");//If you have a namespace, add a namespace

var instance = asm. CreateInstance ("TestClass");

Type. GetProperty ("Name"). SetValue (instance, "My Name"); Setting a value for a property

var string = type. GetProperty ("Name"). GetValue (instance);

var method = type. GetMethod ("Add");

Object[] para = {n};

var ret = (int) method. Invoke (Instance,para);

Use dynamic:

Dynamic dy= new TestClass ();

var ret = dy. ADD (+);

Introduction to Var and dynamic collation in C #

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.