Please enable Javascript to correctly display the contents on Dot Net Tricks!
C# Questions & Answers

Explain the new features of C# 4.0?

The new features of C# 4.0 are given below:

Dynamic binding

This feature is derived from dynamic languages such as Python, Ruby and JavaScript which resolve the types and members at runtime instead of compile time.

dynamic d = "hello c#";
Console.WriteLine(d.ToUpper()); // HELLO C#
Console.WriteLine(d.Show()); // Compiles OK, but gives error at runtime

Optional parameters

In C# 4.0, methods parameters can be specified as optional by providing a default value. When the method having optional parameter is invoked, optional parameters can be omitted.

void Sum(int a, int b = 10)
{
 Console.WriteLine(a+b);
}

Above method can be called as:

Sum(5); // 15

Named arguments

In C# 4.0, any argument can be passed by parameter name instead of parameter position. The Sum() can be called as :

Sum(b:5,a:10); // 15

Type variance

C# 4.0, allows generic interfaces and generic delegates to mark their type parameters as covariant or contravariant. This enables the following code to work:

IEnumerable<string> str;
//TO DO: assign values to str
IEnumerable<object> obj = str;

COM specific interoperability features

Dynamic binding as well as named and optional arguments help making programming against COM less painful than today. On top of that, however, we are adding a number of other features that further improve the interoperability experience specifically with COM.