.NET 4.0 Dynamic

There is a built in type now in .NET 4.0 called “dynamic.”  Just as its name implied its a lose type, it has an infinite amount of properties and methods…(reminds me of python)  This should not be confused with “var” which is a strongly typed lazy-man’s variable. 

 

Dynamic is whatever you want it to be quick example… 

 

The below code illustrates the use of dynamics.   I have declared a simple class that has two properties (Name and Description) and one method PrintUsingReflection…

 

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Reflection;

namespace BlogTests
{
    public class Test
    {
        public string Name { get; set; }
        public string Description { get; set; }

        public void PrintUsingReflection(object test)
        {
            string name = test.GetType().GetProperty("Name")
			    .GetValue(test, null) as string;
            string Description = test.GetType()
			   .GetProperty("Description")
			   .GetValue(test, null) as string;

            Console.WriteLine("Hello there " 
			    + name + " description"
				+ Description);
        }
    }

    [TestClass()]
    public class DynamicExample
    {
        [TestMethod]
        public void ThisIsATest()
        {
            object test = new Test()
            {
                Name = "Nick",
                Description = "Nicks Dynamic Variable!"
            };

            PrintUsingDynamics(test);
        }

        private void PrintUsingDynamics(object test)
        {
            dynamic dynamicTest = test;
            Console.WriteLine("Hello there " + 
			   dynamicTest.Name + " description" +
			   dynamicTest.Description);
            dynamicTest.PrintUsingReflection(test);
        }
    }
}

 

Lets start with the test method called ThisIsATest()..

I am going to start by initializing a class called Test and then cast it to an object…

object test = new Test()
{
    Name = "Nick",
    Description = "Nicks Dynamic Variable!"
};
PrintUsingDynamics(test);

I then pass the object to PrintUsingDynamics() within the method you will see:

dynamic dynamicTest = test;
Console.WriteLine("Hello there " + dynamicTest.Name + " description" + dynamicTest.Description);

I take the provided object(which is really a “Test” class) and assign it to the “dynamicTest” variable.  At this point it is now a lose type…

In case you don’t believe me.. lets see what intellisense has to say about “dynamicTest.”

 

Dynamic_AutoComplete

 

Inside my Console.WriteLine i then attempt to access the Name and Description properties… then the black magic of dynamics takes over.  Volia! 

“Hello there Nick Nicks Dynamic Variable”.. displays. 

 

Back in the day we would have had to have done some really code heavy reflection:

private void PrintUsingReflection(object test)
{
    string name =  
	   test.GetType()
	     .GetProperty("Name")
		 .GetValue(test, null) as string;
    string Description =    
	   test.GetType()
	     .GetProperty("Description")
		 .GetValue(test, null) as string;

   Console.WriteLine("Hello there " + name  + 
                    " description" + Description);
}

Now if you look at the line after we print out "Hello there..” you will see dynamicTest.PrintUsingReflection(test);

dynamic dynamicTest = test;
Console.WriteLine("Hello there " + dynamicTest.Name + " description" + dynamicTest.Description);
dynamicTest.PrintUsingReflection(test);

Which is an example of accessing a “method” on a dynamic type.  At runtime the compiler crosses its fingers, and then calls the method PrintUsingReflection and hopes that the method exists… and volia!  Once again

“Hello there Nick Nicks Dynamic Variable”.. displays. 

 

This has been around for a while… but its incredibly useful!

 

Which one is easier (correct answer is dynamics)….?  The basic premise is whatever you type has to exist.. the compiler basically skips compile time checking.. and at runtime will resolve any property/method calls so be careful!

 

This comes in handy when doing things with “DataItems” that are anonymous types… avoids you having to create some type of “internal” type just so you can get to the data you need..

Advertisements
Tagged with: , , , , ,
Posted in C#, General, LinkedIn, Microsoft, Programming

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: