What is the difference between var and dynamic and how to correctly use dynamic ?, Vardynamic

Source: Internet
Author: User

What is the difference between var and dynamic and how to correctly use dynamic ?, Vardynamic

Many keywords in C # are easy to confuse. var and dynamic are one of them. They can declare dynamic variables, but they have many differences in nature. Var has determined the type in the compilation phase. during initialization, the initialization value must be provided, while dynamic does not. It determines the type only at runtime.

1 // var has determined the type in the compilation phase. 2 // var varError; 3 var isIntType = 3; 4 isIntType. toString (); 5 // dynamic does not perform any 6 // type check during compilation, but puts the type check to 7 // 8 dynamic dyn = 3 during runtime; 9 // dynamic dynOk; 10 dyn = "hello world"; 11 // The error string does not have the [fn nonexistent method] Method 12 // but it is passed during syntax check, syntax Error 13 var s = dyn. fn nonexistent method (); // runtime error

Because dynamic checks the type only at run time, sometimes an error occurs, so it must be used properly. When will it be more convenient to use it? We first define a Person class, and then use reflection to dynamically call the Talk method:

1     class Person2     {3         public void Talk(string msg)4         {5             MessageBox.Show(msg);6         }7     }
1 // dynamic can simplify Code 2 System during reflection. type t = typeof (Person); 3 var obj = Activator. createInstance (t, null); 4 t. invokeMember ("Talk", System. reflection. bindingFlags. invokeMethod, null, obj, new object [] {"hell world! "});

During reflection, method calls of traditional methods are often cumbersome, while dyanmic is simplified and intuitive:

1 dynamic obj2 = Activator.CreateInstance(t, null);2 obj2.Talk("hell world!");

Therefore, as long as dynamic uses the method, it is a very good feature of C.

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.