Correct usage of dynamic in C #

Source: Internet
Author: User

Dynamic is a new feature of framework4.0. The emergence of dynamic makes C # have the characteristics of the weak language type. The compiler does not check the type during compilation. By default, the dynamic object supports any of the features you want during compilation. For example, even if you have no idea about the object returned by the getdynamicobject method, you can call the code as follows, and the compiler will not report an error:

 

Dynamic dynamicobject = getdynamicobject ();
Console. writeline (dynamicobject. Name );
Console. writeline (dynamicobject. samplemethod ());

When it comes to correct usage, we should first point out an incorrect usage:

It is often used to compare the keyword var with dynamic. In fact, VaR and dynamic are completely two concepts and should not be put together for comparison. VaR is actually the "syntactic sugar" thrown to us during the compilation period. Once compiled, the actual type of the VaR variable will be automatically matched during the compilation period, and the declaration of the variable will be replaced with the actual type, this seems like we declare it with the actual type during encoding. After dynamic is compiled, it is actually an object type, but the compiler will perform special processing on the dynamic type so that it does not perform any type check during compilation, instead, the type check is placed at runtime.

This can be seen from the Visual Studio editor window. Variables declared with VAR support "smart sensing", because visual studion can deduce the actual type of VaR, while variables declared with dynamic do not support "smart sensing ", because the compiler has no idea about the types in its runtime. When you use "smart sensing" for dynamic variables, the system prompts "this operation will be parsed at runtime ".

The dynamic variable is an object variable, which can be verified by using the Il code. The IL code is not pasted here. Of course, the compiler also processes the dynamic declaration to distinguish the direct object variable.

Dynamic is rendered in msdn to simplify interoperability. I feel that it is based on this that some developers misunderstand: because many developers do not have access to coding such as COM + and office secondary development, a dynamic application is urgently needed. In daily development, I think dynamic is very valuable:

Type conversionSwitching between dynamic instances and other types of instances is very simple. developers can easily switch between dyanmic and non-dynamic behaviors. All instances can be implicitly converted to dynamic instances. See the following example: Dynamic d1 = 7; Dynamic D2 = "a string"; Dynamic D3 = system. datetime. today; Dynamic D4 = system. diagnostics. process. getprocesses (); conversely, an implicit conversion can be dynamically applied to any expression of type dynamic. and vice versa. Any expression of type dynamic can be implicitly converted to another type. Int I = D1; string STR = d2; datetime dt = D3; system. Diagnostics. Process [] procs = D4; Method overload with dynamic type parametersIf a method is called to pass an object of the dynamic type, or the called object is of the dynamic type, the overloaded judgment occurs at runtime rather than during compilation. Dynamic Language Runtime (Dynamic Language Runtime DLR) is. NET framework 4 Beta 1 provides support for the dynamic type in C #, and implements dynamic programming languages such as ironpython and ironruby.

Dynamic simplifies reflection.

Previously we used reflection like this:

 

Public class dynamicsample
{
Public string name {Get; set ;}

Public int add (int A, int B)
{
Return A + B;
}
}
Dynamicsample = new dynamicsample (); // create instance I did not use reflection to simplify the demo
VaR addmethod = typeof (dynamicsample). getmethod ("add ");
Int Re = (INT) addmethod. Invoke (dynamicsample, new object [] {1, 2}); now we have a simplified Syntax: Dynamic dynamicsample2 = new dynamicsample ();
Int re2 = dynamicsample2.add (1, 2 );

We may disagree with this simplification. After all, it seems that the Code has not been much reduced. However, if efficiency and beauty are taken into account, the advantages of dynamic will become apparent. The compiler optimizes dynamic, which is much more efficient than reflection without caching. If comparison is required, you can run the code (call the add method part) of the above two to run 1000000 to draw a conclusion.

Dynamic is a new feature of framework4.0. The emergence of dynamic makes C # have the characteristics of the weak language type. The compiler does not check the type during compilation. By default, the dynamic object supports any of the features you want during compilation. For example, even if you have no idea about the object returned by the getdynamicobject method, you can call the code as follows, and the compiler will not report an error:

 

Dynamic dynamicobject = getdynamicobject ();
Console. writeline (dynamicobject. Name );
Console. writeline (dynamicobject. samplemethod ());

When it comes to correct usage, we should first point out an incorrect usage:

It is often used to compare the keyword var with dynamic. In fact, VaR and dynamic are completely two concepts and should not be put together for comparison. VaR is actually the "syntactic sugar" thrown to us during the compilation period. Once compiled, the actual type of the VaR variable will be automatically matched during the compilation period, and the declaration of the variable will be replaced with the actual type, this seems like we declare it with the actual type during encoding. After dynamic is compiled, it is actually an object type, but the compiler will perform special processing on the dynamic type so that it does not perform any type check during compilation, instead, the type check is placed at runtime.

This can be seen from the Visual Studio editor window. Variables declared with VAR support "smart sensing", because visual studion can deduce the actual type of VaR, while variables declared with dynamic do not support "smart sensing ", because the compiler has no idea about the types in its runtime. When you use "smart sensing" for dynamic variables, the system prompts "this operation will be parsed at runtime ".

The dynamic variable is an object variable, which can be verified by using the Il code. The IL code is not pasted here. Of course, the compiler also processes the dynamic declaration to distinguish the direct object variable.

Dynamic is rendered in msdn to simplify interoperability. I feel that it is based on this that some developers misunderstand: because many developers do not have access to coding such as COM + and office secondary development, a dynamic application is urgently needed. In daily development, I think dynamic is very valuable:

Type conversionSwitching between dynamic instances and other types of instances is very simple. developers can easily switch between dyanmic and non-dynamic behaviors. All instances can be implicitly converted to dynamic instances. See the following example: Dynamic d1 = 7; Dynamic D2 = "a string"; Dynamic D3 = system. datetime. today; Dynamic D4 = system. diagnostics. process. getprocesses (); conversely, an implicit conversion can be dynamically applied to any expression of type dynamic. and vice versa. Any expression of type dynamic can be implicitly converted to another type. Int I = D1; string STR = d2; datetime dt = D3; system. Diagnostics. Process [] procs = D4; Method overload with dynamic type parametersIf a method is called to pass an object of the dynamic type, or the called object is of the dynamic type, the overloaded judgment occurs at runtime rather than during compilation. Dynamic Language Runtime (Dynamic Language Runtime DLR) is. NET framework 4 Beta 1 provides support for the dynamic type in C #, and implements dynamic programming languages such as ironpython and ironruby.

Dynamic simplifies reflection.

Previously we used reflection like this:

 

Public class dynamicsample
{
Public string name {Get; set ;}

Public int add (int A, int B)
{
Return A + B;
}
}
Dynamicsample = new dynamicsample (); // create instance I did not use reflection to simplify the demo
VaR addmethod = typeof (dynamicsample). getmethod ("add ");
Int Re = (INT) addmethod. Invoke (dynamicsample, new object [] {1, 2}); now we have a simplified Syntax: Dynamic dynamicsample2 = new dynamicsample ();
Int re2 = dynamicsample2.add (1, 2 );

We may disagree with this simplification. After all, it seems that the Code has not been much reduced. However, if efficiency and beauty are taken into account, the advantages of dynamic will become apparent. The compiler optimizes dynamic, which is much more efficient than reflection without caching. If comparison is required, you can run the code (call the add method part) of the above two to run 1000000 to draw a conclusion.

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.