A .Net 4.0 tidbit to whet your excitement!

This is just a very tiny item to stoke the coals of your excitement about the .Net 4.0!

 

I know this will seem pretty simple but dealing with COM objects or DOM or other externally bound type structures can be pretty tedious if you cannot statically bind to those type libraries.   For example, if you are calling a Calculator object, if you can statically bind and invoke, the code is pretty simple:

 

       // Static Invocation

       Calculator calc = GetCalculator();

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

 

 

However, if you cannot statically bind, you have to go thru the tedious way of doing dynamic invocation.   The code would looks something like this:

 

       // v3.x .Net Dynamic Invocation

       object calc = GetCalculator();

       Type calcType = calc.GetType();

       object result = calcType.InvokeMember("Add", BindingFlags.InvokeMethod, null, new object[] { 10, 20 });

       sum = Convert.ToInt32(result);

 

 

The above works, but the code is messy and will look somewhat different across the different languages.  Here comes .Net 4.0 DLR!!  With the new dynamic keyword the code not only becomes MUCH simpler, but is almost consistent across the languages!!!  Take a look!

 

       // v4.0 .Net Dynamic Invocation using the DLR!

       dynamic calc = GetCalculator();

       sum = calc.Add(10, 20);

 

 

This is exciting stuff!    Happy Coding!!

Advertisements
This entry was posted in Development. Bookmark the permalink.

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