Introduction- The major aim of C# 4.0 is dynamic programming.More importantly objects are dynamic and there behaviour and properties are not accessed by a static type. Followings are some example – 1. objects from dynamic programming languages 2. ordinary .NET types accessed through reflection 3. objects with changing structure, such as HTML DOM script objects 4. data readers and other user defined dynamic object The new features are as follows –
Dynamic type–
In C# 4.0 a new keyword is introduced:” dynamic ” and it’s used to tell the compiler that the object is defined at runtime. A dynamic object is assumed to support any operation at compile time.
dynamic objCust =GetCustomer(); objCust.FirstName ="John" ; objCust.LastName ="Cena" ; objCust.CalculateSalary();
In this case, the variable objCust is declared dynamic, in this way , the C# compiler that the type of Customer is not known until run time, but it can dispatch messages to it. For example, at run time, the compiler discovers the properties to be called (FirstName and LastName) and the method CalculatedSalary which is resolved only on execution. This way, the dynamic run time receives information about the call such as its name and parameters. With this information, application can call the right function (in Iron-Python). If the method is not defined, then an exception of type RuntimeBinderException is thrown.
Named and optional arguments
Another new feature is named and optional arguments/parameters. Optional parameters allow giving a method parameter a default value, so you don’t have to specify it every time you can call the method directly.
using System; using System.Collection.Generic ; using System.Linq ; using System.Text ; namespace CSharpNewFeatures { class Demo { public static void MyMethod(int age, String name="kshirodra" , double salary=20000) { } static void Main(string[] args) { MyMethod(23); MyMethod(23,"Kshirodra"); MyMethod(23,"Kshirodra",20000); MyMethod(23 ,salary:20000); } } }
Covariance and Contravariance
Another new feature is the use of covariance and contravariance of generics. Covariance allows casting of generic types to the base types, for example, IEnumerable will be implicitly convertible an IEnumerable
using System; using System.Collection.Generic ; using System.Linq ; using System.Text ; namespace CSharpNewFeatures { class Demo { static void Main(string[] args) { IList arrNames=new List();//here we have a list of string. IEnumerableobjects =arrNames ;//here converted to an Enumerable collection. } } }