When to use dynamic in C #

Source: Internet
Author: User

Background: For example, there is a method, there are many parameters, and sometimes only need some of the parameters, sometimes need to use all, or even sometimes do not need, this time to write a long parameter list is not cool, and error-prone, it is necessary to consider C # dynamic type as a parameter. This is especially common when manipulating SQL statements.

The code is as follows:

1          Public Static voidtestdynamic ()2         {3Dynamic d =NewExpandoObject ();4D.name ="SHARPL";5D.age = -;6D.city ="Beijing";7 Dosth (d);8         }9 Ten          Public Static voiddosth (Dynamic D1) One         { A             stringTMP =""; -             //to cast a dynamic type to a dictionary type -             varKVS = (idictionary<string,Object>) D1; the             if(KVS. ContainsKey ("Name")) -             { -TMP + ="my name is."+kvs["Name"]; -             } +             if(KVS. ContainsKey (" Age")) -             { +TMP + ="my age is"+ kvs[" Age"]; A             } at             if(KVS. ContainsKey (" Fun")) -             { -TMP + ="my hobby is"+ kvs[" Fun"]; -             } -             if(KVS. ContainsKey (" City")) -             { inTMP + ="my city is"+ kvs[" City"]; -             } to Console.WriteLine (TMP); +         } -}

As above, we may only enter the name, and sometimes we may need to enter all the information, with the dynamic only one method can be solved without entering a long parameter list.

This situation is often used in database queries or inserts, especially in the insert operation, some tables have many fields, we can not always use each field as a parameter, it is really silly, the above code is just an example.

When to use dynamic in 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.