Tuesday, April 14, 2009

C# 4.0 New Exciting Features!

New exciting features of C# 4.0. C# has always been an exciting language. In each version of C# we find many exciting and new features that made our life simpler and easier. C# 4.0 brings us exciting features such as:

  • Dynamically typed objects
  • Named and Optional function parameters
  • Covariance and Contravariance

Dynamically Types Objects
Today, in C# we may have the code to get the instance of class Calculator and then invoke the Add() method on that instance to return an integer.

Calculator calc = GetCalculatorInstance();
int sum = calc.Add(10, 20);

Here all the objects are statically typed i.e. the type of the object is known at compile time. Now, let's take an exmaple where the Calculator class resides in an assembly and we want to invoke the Add() method dynamically through C#. When the phrase "dynamically invoke method" comes, we immediately think of Reflection. Yes, you are correct, we will use reflection to invoke the Add() method as shown below:

object calc = GetCalculatorInstance();
Type type = calc.GetType();
object result = type.InvokeMember("Add",
BindingFlags.InvokeMethod, null,
new object[] { 10, 20 });

int sum = Convert.ToInt32(result);

So far so good. Now what if you don't want to play with reflection?
Yes, you can do so in C# 4.0. Making the use of "statically typed dynamic object" you can achieve the same output as that of reflection. Let's look at the code first, which will make our understanding more clear:

dynamic calc = GetCalculatorInstance();
int result = calc.Add(10, 20);

In the above example we are declaring a variable, calc, whose static type is dynamic. Yes, you read that correctly, we have statically typed our object to be dynamic. We'll then be using dynamic method invocation to call the Add() method and then dynamic conversion to convert the result of the dynamic invocation to a statically typed integer.

I would still encourage you to use static types wherever possible, since they are the best for performance reason.

Named and Optional function parameters
Remember C++'s default values for function parameters that made the parameter in question optional? In C# 4.0 you will be able to do that. In previous version of the language to achieve this type of behavior we use to create overloaded methods with varying parameters. By doing this, number of methods would increase keeping the business logic almost same.

Let's assume that we have the following OpenTextFile method along with three overloads of the method with different signatures. The overloads of the primary method will call the primary method with default values for the arguments expected.

4 arguments (Primary method)
public StreamReader OpenTextFile(
string path,
Encoding encoding,
bool detectEncoding,
int bufferSize) { }

3 arguments (Overloaded method)
public StreamReader OpenTextFile(
string path,
Encoding encoding,
bool detectEncoding) { }

2 arguments (Overloaded method)
public StreamReader OpenTextFile(
string path,
Encoding encoding) { }

1 argument (Overloaded method)
public StreamReader OpenTextFile(string path) { }

In C# 4.0 the primary method can be refactored to use optional parameters as shown below:

Single primary method accepting default values
public StreamReader OpenTextFile(
string path,
Encoding encoding = null,
bool detectEncoding = false,
int bufferSize = 1024) { }

It is now possible to call the OpenTextFile method omitting one or more of the optional parameters.

OpenTextFile("foo.txt", Encoding.UTF8);

It is also possible to provide named parameters and as such the OpenTextFile method can be called omitting one or more of the optional parameters while also specifying another parameter by name.

OpenTextFile("foo.txt", Encoding.UTF8, bufferSize: 4098);

Please note that named arguments must be provided last although when provided they can be provided in any order.

Covariance and Contravariance

An operator between types is said to be covariant if it orders these types from more specific to more general ones. Similarly an operator between types is said to be contravariant if it orders them in the reversed order. Whenever neither of these conditions is met, an operator is said to be invariant.
Eric Lippert has a complete 11 part article on Covariance and Contravariance which describes the matter in details with examples. This is what I was looking for since long :)

Apart from the features mentioned above, C# 4.0 is going to bring a lot more for the developers. Keep watching...


Post a Comment