Correct usage of dynamic keyword in C of recommendation

  • 2021-11-10 10:31:29
  • OfStack

dynamic is a new feature of FrameWork 4.0. The emergence of dynamic gives C # the characteristic of weak language type. The compiler no longer checks the type at compile time, and the default dynamic object at compile time supports any features you want. For example, even if you don't know the object 1 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 one wrong usage:

People often compare the keyword var with dynamic. In fact, var and dynamic are completely two concepts, and should not be compared in one place at all. var is actually the "syntax sugar" thrown to us at compile time. Once 1 is compiled, it will automatically match the actual type of var variable at compile time and replace the declaration of the variable with the actual type, which looks as if we were declaring with the actual type when coding. After dynamic is compiled, it is actually an object type, but the compiler will give special treatment to dynamic type, so that it will not do any type checking during compilation, but put the type checking at runtime.

This can be seen from the editor window of visual studio. Variables declared as var support "IntelliSense" because visual studion can infer the actual type of var type, while variables declared as dynamic do not support "IntelliSense" because the compiler does not know its runtime type 1. Using IntelliSense for the dynamic variable prompts "This operation will be resolved at run time."

The point that the dynamic variable is an object variable can be verified by the IL code, which is no longer posted here. Of course, the compiler also handles dynamic declarations to distinguish direct object variables.

dynamic is greatly exaggerated in MSDN to simplify interoperability. I feel that it is based on this point that some developers misunderstand it: because many developers will not be exposed to codes such as COM + and OFFICE 2 development, there is an urgent need for an application reason of dynamic. So, in daily development, I think one valuable point of dynamic is:

Type conversion

The conversion between Dynamic type instances and other types of instances is straightforward, and developers can easily switch between dyanmic and non-dynamic behaviors. Any instance can be implicitly converted to an dynamic type instance, as shown in 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 also be implicitly converted to another type.


int i = d1;
string str = d2;
DateTime dt = d3;
System.Diagnostics.Process[] procs = d4;

Overloading problem with dynamic type parameters in methods

If a method is invoked to pass an object of type dynamic, or if the object being invoked is of type dynamic, the overload determination occurs at runtime, not at compile time.

Dynamic Language Runtime (dynamic language runtime DLR)

The dynamic language runtime is a new set of API in NET Framework 4 Beta 1 that provides support for the dynamic type in c # and also implements dynamic programming languages such as IronPython and IronRuby.

dynamic simplifies reflection.

We used to use reflection like this:


public class DynamicSample
{
public string Name { get; set; }
public int Add(int a, int b)
{
return a + b;
}
}
DynamicSample dynamicSample = new DynamicSample(); //create instance To simplify the demonstration, I didn't use reflection 
var addMethod = typeof(DynamicSample).GetMethod("Add");
int re = (int)addMethod.Invoke(dynamicSample, new object[] { 1, 2 });

Now, we have a simplified way of writing:


dynamic dynamicSample2 = new DynamicSample();
int re2 = dynamicSample2.Add(1, 2);

We may not be impressed with this simplification, after all, it seems that the code has not been reduced much, but if we consider the two characteristics of efficiency and beauty, the advantages of dynamic will appear. The compiler optimizes dynamic to be much faster than reflection without caching. If you have to compare, you can run the code of the above two (calling the Add method section) for 1000000 to reach a conclusion.

COM Interoperability

C # 4.0 includes several features that improve interoperability with traditional COM API interfaces such as Office automation. Dynamic types, named parameters, and optional parameters are also part 1 of the improvement.

Many COM methods allow their parameters and return values to be object, so for strongly typed languages such as C #, a lot of casting is required. However, in C # 4.0, if the/link option is added at compile time, the dynamic type has a new effect: It makes the object type (parameter type or return type) in the COM interface method signature be treated as dynamic, thus avoiding a lot of type conversion work. For example, the following statement compares this.


//  No use  dynamic.
((Excel.Range)excel.Cells[1, 1]).Value2 = "Name";
Excel.Range range = (Excel.Range)excel.Cells[1, 1];
//  Used dynamic, 
excel.Cells[1, 1].Value = "Name";
Excel.Range range = excel.Cells[1, 1];

Related articles: