C# 4.0 Dynamic Lookup

One of the core features introduced in C# 4.0 is called Dynamic Lookup which allows a unified approach to invoking things dynamically. Currently, when you call object methods or properties, the compiler checks that they exist and raises an error if they do not. With dynamic lookup, you can call any method or property, and they are not checked until runtime. C# 4.0 is extending towards the dynamic languages.

 
C# 4.0 will support dynamic typing through a new static type called “dynamic”. As already described, when you have an object of type dynamic you can do whatever you like with it, those operations are resolved only at runtime. Lets first see a method declaration:
 
public dynamic GetService()
{
    // Getting some service…
}
 
and how to use it:
 
dynamic service = GetService();
service.Do("YourJob");
 
The C# compiler allows you to call a method with any name and any arguments because service is declared as dynamic. SOnly at runtime will you get an error if the returned object doesn’t have such a method.

Local Type Inference (C#)

C# 3.0 was released as a part of the Microsoft .NET 3.5 Framework. In this blog post, I’ll cover the local type inference feature of C# 3.0. Through local type inference you can define variables with the var keyword and the compiler will figure out the type for you at compile time and replace it. It is great for results from query expressions as show in the example below. It may appear that it is untyped or even give the impression it is a variant. It is not. It is a strongly typed object whose type is set at compile time.
 
var i = 5;
int i = 5;
 
string[] words = { "cherry", "apple", "blueberry" };
 
var sortedWords =
   from w in words
   orderby w
   select w;