C #4.0 new dynamic, optional parameters, and naming Parameters

Source: Internet
Author: User

1. dynamic ExpandoObject
Anyone familiar with js knows that js can be written like this:

1 var t = new Object(); 2 t.Abc = ‘something’; 3 t.Value = 243;

We can also use this js Dynamic Language Feature in c #, provided that a variable is declared as the ExpandoObject type. For example:

1 static void Main( string [] args) 2 { 3 dynamic t = new ExpandoObject(); 4 t.Abc = "abc" ; 5 t.Value = 10000; 6 Console.WriteLine( "ts abc = {0},ts value = {1}" , t.Abc, t.Value); 7 Console.ReadLine(); 8 }

C #4.0 adds a namespace System. dynamic is used to support this application. What is the significance of this usage? I am not sure yet. It is also a test of c #'s transition to Dynamic Language.

2. Automatic generic Conversion

The following code cannot be compiled before C #4.0.

1 IEnumerable< object > objs = new List< string > { 2          "Im 0" , "Iam 1" , "Iam 2" 3      };

However, in c #4.0, this declaration is allowed, but it is also limited to generic interfaces. A similar generic method is not allowed. The following code has compilation errors:

1 List< object > objList = new List< string > {  2          "Iam 0" , "Iam 1" , "Iam 2" 3      };

3. Optional parameters of method parameters
Syntax declared in the following method

1 static void DoSomething( int notOptionalArg, string arg1 = "default Arg1" , string arg2 = "default arg2" ) { 2      Console.WriteLine( "arg1 = {0},arg2 = {1}" ,arg1,arg2); 3 }

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.