C #4.0 Dynamic Programming & named argument

Source: Internet
Author: User
Document directory
  • Dynamic Programming
  • Named argument

From: Code project View Original

Dynamic Programming

C #4.0 supports dynamic programming by introducing newDynamic typed objects.The type of these objects is resolved at run-time instead of at compile-time. A New Keyword dynamic is introduced to declare dynamic typed object. the keyword tells the compiler that everything to do with the object, declared as dynamic, shocould be done dynamically at the Run-Time Using Dynamic Language Runtime (DLR ). remember dynamic keyword is different from VAR keyword. when we declare an object as VAR, it is resolved at compile-time whereas in case of dynamic, the object type is dynamic and it's resolved at run-time. let's do some coding to see the advantage of dynamic typed objects.

A year ago, I wrote a code of setting the property of an object Using Reflection:

Collapse copy code
   1:  Assembly asmLib= Assembly.LoadFile(@"C:/temp/DemoClass/bin/Debug/DemoClass.dll");   2:  Type demoClassType = asmLib.GetType("DemoClass.DemoClassLib");   3:  object demoClassobj= Activator.CreateInstance(demoClassType);   4:  PropertyInfo pInfo= demoClassType.GetProperty("Name");   5:  pInfo.SetValue(demoClassobj, "Adil", null);

Notice lines 3-5 create instance'demoClassType'And set properties'Name'To'Adil'. Now with C #4.0, line #3-5 can be written as simple:

Collapse copy code
dynamic dynamicDemoClassObj = Activator.CreateInstance(demoClassType);dynamicDemoClassObj.Name = "Adil";

Simple, isn' t it? Let's see a slide from Anders hejlsberg's session at PDC 2008:

From the above slide, you can call method (s) suchx.ToString(),y.ToLower(),z.Add(1), Etc. And it will work smoothly.
This feature is great and provides much flexibility for developers. of course there are pros and cons of dynamic programming as well but where C # is going is something like having features of both static versions ages and dynamic versions ages.

Optional parameters

The second feature is optional parameters. Let's say I have a classEmployeeAnd I provide few overloads of the constructor to enable making certain parameters as optional as follows:

Collapse copy code
 public class Employee    {        public string FirstName { get; set; }        public string LastName { get; set; }        public string Qualification { get; set; }        public string MiddleName { get; set; }        public Employee(string firstName, string lastName)        {            FirstName= firstName;            LastName= lastName;            Qualification= "N/A";            MiddleName= string.Empty;        }        public Employee(string firstName, string lastName, string qualification)        {            FirstName= firstName;            LastName= lastName;            Qualification= qualification;            MiddleName= string.Empty;        }        public Employee(string firstName, string lastName, string qualification,            string middleName)        {            FirstName= firstName;            LastName= lastName;            Qualification= qualification;            MiddleName= middleName        }    }

With C #4.0, you need to create just one constructor for that as follows:

Collapse copy code
public Employee(string firstName, string lastName,            string qualification = "N/A", string middleName = ""){    FirstName= firstName;    LastName= lastName;    Qualification= qualification;    MiddleName = middleName;}

As simple as that and you can easily call that as follows:

Collapse copy code
Employee(“Adil”,”Mughal”);

This feature was available in some other ages but was for some reason not provided in C # yet, but now it's available. this feature has a good impact in COM InterOP which allows developers to skip missing parameters which we will hopefully see in later post (s ). finally, the compiler will always fill the optional parameters by their default given values, if you do not provide them. for instance, in our current case, it will be:

Collapse copy code
Employee emp= newoyee("Adil", "Mughal");

Simple but useful feature!

Named argument

So, we discussed an exampleEmployeeClass in which we passed some optional parameters in the constructor:

Collapse copy code
public Employee(string firstName, string lastName, string qualification = "N/A", string middleName = "")

And I can simply call that as shown below:

Collapse copy code
Employee emp= new Employee("Adil", "Mughal");

A question can be raised "Is there any way that we can skip qualification, I. e. Third parameter and give the last parametermiddleName? "

The answer of this question is "Yes Absolutely, we can and that feature is calledNamed argumentIn C #4.0. "We can simply do this like:

Collapse copy code
Employee emp = new Employee("Adil", "Mughal", middleName: "Ahmed");

Good enough to answer the query. :). Now let's make some changes withEmployee Constructor and makelastName Optional as well:

Collapse copy code
public Employee(string firstName, string lastName = "", string qualification = "N/A", string middleName = "")

Now I can instantiate objectEmployeeIn quite simple and flexible ways:

Collapse copy code
Employee("Adil", qualification:"BS");Employee("ABC", lastName: "EFG", qualification: "BS");Employee("XYZ", middleName: "MNO");
Conclusion

These upcoming features are really cool as they will enable C # developers to be more productive with the help of dynamic programming and optional parameters though some of the features are not new in the programming ages 'World.

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.