Understand the differences between C #4 Dynamic (1)-var, object, and dynamic and the use of dynamic

Source: Internet
Author: User
Original article: understanding the differences between C #4 Dynamic (1)-var, object, and dynamic and the use of dynamic

Reading directory:

I. Why are the three of them

Ii. Reasons for arbitrary assignment

Iii. Usage of dynamic

Iv. Precautions for using dynamic

I. Why are the three of them?

The reason for the comparison is that they are very similar in use. You can use the variables they declare to assign values of any type.

Take a look at the following example:

var a = 1;object b = 1;dynamic c = 1;

You can also use keywords to assign more complex types to them.

var a = new string[]{"1"};object b = new string[]{"1"};dynamic c = new string[]{"1"};
Ii. Reasons for arbitrary assignment

In the above example, the three seem very similar, but the principle behind them is very different.

VaR is introduced in C #3. In fact, it is just a syntactic sugar. var itself is not a type, and the other two objects and dynamic are types.

The variable declared by VAR has determined its type at the moment of value assignment.

So if you use this method, there will be a compilation error:

var a = 1;a = "Test";

 

The reason why an object can be assigned a value of any type is actually known, because all types are derived from the object. Therefore, it can be assigned a value of any type:

object a = 1;a = "Test";

 

What about dynamic?

It is a new type introduced by C #. It is characterized by variables declared as dynamic types, rather than determining the actual type during compilation, but at runtime.

Therefore, the following code can be compiled, but an error will be reported during running:

dynamic a = "test";a++;

What is the internal processing process of the above Code?

First, the dynamic type is assigned to the string "test". When you run the ++ operation ,. net searches for whether the ++ operation is supported in the current value type string. If not, an exception occurs.

Therefore, if you modify the code in this way, the code can run normally.

dynamic a = "test";a = 1;a++;
Iii. Dynamic usage 1 directly use this type to easily insert attributes and Methods
static void Main(string[] args){    dynamic person = new System.Dynamic.ExpandoObject();    person.Name = "cary";    person.Age = 25;    person.ShowDescription = new Func<string>(() => person.Name + person.Age);     Console.WriteLine(person.Name + person.Age + person.ShowDescription());    Console.ReadLine();}
2 Enumerate all members
foreach (var property in (IDictionary<String, Object>)dynEO){     Console.WriteLine(property.Key + ": " + property.Value);}
3. Simplified reflection

Examples of common reflection processing:

object calc = GetCalculator();Type calcType = calc.GetType();object res = calcType.InvokeMember( "Add", BindingFlags.InvokeMethod, null, new object[] { 10, 20 });int sum = Convert.ToInt32(res);

After using dynamic:

 dynamic calc = GetCalculator(); int sum = calc.Add(10, 20);

 

4. Precautions for using dynamic

With dynamic ,. net and has the advantage of dynamic types, but because all operations of the dynamic type are determined at runtime, all errors cannot occur during compilation and use, you need to be very careful.

Because dynamic is of the type, if the function accepts a parameter of the determined type, the dynamic type cannot be passed in, resulting in a compilation error. For example:

public int Add(int a, int b){    return a + b;}dynamic test1 = 1;dynamic test2 = 2;Add(test1, test2);

The following is the above example. Thank you for [email protected]. You can try it out.

    1. # 15th floor[Email protected]Why is no error reported when I copy your last example? Supports (0) Objection (0) reply reference Deletion
    2. # 16th floor [main poster]Justrun@ [Email protected]
      It should be that the compilation fails. I will try to support (0) against (0) Modification and deletion later.
    3. #17 floor [main poster]Justrun@ [Email protected]
      No error is reported. For common types such as int, there will be no problem.
      However, if it is of the object type, an error is reported during running.

 

In addition, when writing a function, we 'd better not use the dynamic type as a function parameter. This is like using an object as a function parameter, which will cause subsequent troubles for program maintenance.

No one can determine what the user passed in, and there will be no problem during compilation. If an error occurs during running, it may be a disaster.

Understand the differences between C #4 Dynamic (1)-var, object, and dynamic and the use of dynamic

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.