[C#] Dynamic Types

C# 4 (.NET 4) introduced a new keyword “dynamic”. What is it for? C# only supports strongly typed variables. So what are the dynamic types and how do they work?

1. var Variables

When you assign a variable using the “var” keyword, the variable is still strongly typed. You cannot assign any type of values to it.

var strValue = "Hello";
strValue = 10; // error

This code won’t be compiled. You cannot assign integer to a string variable.

2. dynamic Variables

The “dynamic” keyword is introduced in C#4. Let’s start with an example.

public static void Test1()
{
  dynamic value = 10;
  Console.WriteLine(value.GetType());

  value = "Hello";
  Console.WriteLine(value.GetType());

  value = new StringBuilder();
  Console.WriteLine(value.GetType());
}

surprisingly, the code works without errors. The result is “System.Int32, System.String, System.Text.StringBuilder“.

At a specific moment, each dynamic variable looks that it has a type. But you can assign any type of value to a dynamic variable and it changes its type.

3. Dynamic Behavior

so far, a dynamic variable looks like, well, dynamic. But look at the following example:

dynamic value = "Hello";
Console.WriteLine("Length: {0}", value.Length); // 5
Console.WriteLine("Length: {0}", value.Size); // ?

The “String” type has the “Length” property but does not have the “Size” property. You might expect compile errors. But you won’t get any compile errors but the application will crash at runtime.

You will get the following error: “Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: ‘string’ does not contain a definition for ‘Size’

What’s going on here? You already noticed that you did not get “IntelliSense” when you worked with the “dynamic” keyword.

Now we can figure out one of the most important features of dynamic types:

  • The type of dynamic variable is static at any moment but will not be evaluated until runtime.

What does this behavior mean to developers? What are the benefits?

4. What For?

If you are like me, you might think that dynamic variables does not have any helpful features. Rather they encourage somewhat bad programming practice.

Actually, the use of the “dynamic” keyword is limited:

  • Calling JavaScript method from Silverlight
  • Referring to objects returned from a COM or DOM API
  • Referring to objects obtained from a dynamic language (IronRuby, for example)
  • Referring to objects from reflection

5. ExpandoObject Class

There is another way to use dynamic variable in an interesting way.

The “System.Dynamic.ExpandoObject” represents an object whose members can be dynamically added and removed at run time.

  • Create an instance of “ExpandoObject
  • Assign the object to the dynamic variable
  • You can add any properties at any time
  • To create a method, you need to use a delegate
// ExpandoObject myObj = new ExpandoObject(); // without dynamic, there are compile errors
dynamic myObj = new ExpandoObject(); // bypass type checking

// Add Properties
myObj.Greeting = "Hello";
myObj.ToWhom = "World";

// Add a Method
myObj.Say = (Action)(() => { Console.WriteLine("{0} {1}", myObj.Greeting, myObj.ToWhom); });

// Invoke the Method
myObj.Say();

The code works magically.

 

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s