Thursday, 5 November 2009

C# 4.0 New Features

C# 4.0 Major new features - 4 major groups:
  1. Dynamic lookup
  2. Named and optional parameters
  3. COM specific interop features
  4. Variance
1. Dynamic lookup
It's a new feature which allows you to write the following at runtime: method, operator, property and object invocations.
  • The validation of operations of a dynamic object is made at runtime not compile time. So if you have written an incorrect expression, you will only get the error message at runtime.
  • DLR (Dynamic Language Runtime) is a new component which runs on top of CLR (Common Language Runtime) and provides dynamic services to C# 4.0.
Create a dynamic object:

dynamic d = GetDynamicObject();
d.M(4); // call a method
d.P = 2; // setting a property
d[1] = 3 // setting through indexers
int i = d + 3; // calling operators
string s = d(5,7); // invoking as a delegate
d = new Employee(); // assigning a static type to a dynamic type
var testInstance = new ExampleClass(d); // testInstance is a static type of ExampleClass not a dynamic type

M will be examined at runtime not compiletime. if d doesn't have a method called M, compiler ignores the error and it indeed at runtime an exception will occur.

What is a dynamic type anyway?
dynamic is a static type an instance of which bypasses the compile-time type checking. In other words, type checking will be defered to runtime.

So, you can use "is" and "as" with a dynamic type:

int i = 8;
dynamic d;
// With the is operator.
// The dynamic type behaves like object. The following
// expression returns true unless someVar has the value null.
if (someVar is dynamic) { }

// With the as operator.
d = i as dynamic;


dynamic d = 7; // implicit conversion

int i = d; // assignment conversion

In C# 3.0:

((Excel.Range)excel.Cells[1, 1]).Value2 = "Name";

whereas in C# 4.0:

excel.Cells[1, 1].Value = "Name";

run-time COM binder in DLR will handle the conversion.

In C# 3.0 this raises an exception at compile time:

object obj = 1;
obj = obj + 3;

Whereas in C# 4.0, this raises an exception neither in compile-time nor in run-time:

dynamic dyn = 1;
dyn = dyn + 3;

Passing a dynamic object to a static method:

Foo foo = new Foo();
dynamic d = new Bar();
var result = foo.M(d);

foo is a static object whereas d is a dynamic object. result would be a dynamic object itself because d which is a dynamic object has been passed to M method of foo.


... to be updated

No comments: