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.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: