What Is the 'Dynamic' Type in C# 4.0 Used For

What is the 'dynamic' type in C# 4.0 used for?

The dynamic keyword is new to C# 4.0, and is used to tell the compiler that a variable's type can change or that it is not known until runtime. Think of it as being able to interact with an Object without having to cast it.

dynamic cust = GetCustomer();
cust.FirstName = "foo"; // works as expected
cust.Process(); // works as expected
cust.MissingMethod(); // No method found!

Notice we did not need to cast nor declare cust as type Customer. Because we declared it dynamic, the runtime takes over and then searches and sets the FirstName property for us. Now, of course, when you are using a dynamic variable, you are giving up compiler type checking. This means the call cust.MissingMethod() will compile and not fail until runtime. The result of this operation is a RuntimeBinderException because MissingMethod is not defined on the Customer class.

The example above shows how dynamic works when calling methods and properties. Another powerful (and potentially dangerous) feature is being able to reuse variables for different types of data. I'm sure the Python, Ruby, and Perl programmers out there can think of a million ways to take advantage of this, but I've been using C# so long that it just feels "wrong" to me.

dynamic foo = 123;
foo = "bar";

OK, so you most likely will not be writing code like the above very often. There may be times, however, when variable reuse can come in handy or clean up a dirty piece of legacy code. One simple case I run into often is constantly having to cast between decimal and double.

decimal foo = GetDecimalValue();
foo = foo / 2.5; // Does not compile
foo = Math.Sqrt(foo); // Does not compile
string bar = foo.ToString("c");

The second line does not compile because 2.5 is typed as a double and line 3 does not compile because Math.Sqrt expects a double. Obviously, all you have to do is cast and/or change your variable type, but there may be situations where dynamic makes sense to use.

dynamic foo = GetDecimalValue(); // still returns a decimal
foo = foo / 2.5; // The runtime takes care of this for us
foo = Math.Sqrt(foo); // Again, the DLR works its magic
string bar = foo.ToString("c");

Read more feature : http://www.codeproject.com/KB/cs/CSharp4Features.aspx

C# 4: Real-World Example of Dynamic Types

There are lots of cases where you are already using dynamic typing and dynamic binding today. You just don't realize it, because it is all hidden behind strings or System.Object, since until C# 4, the necessary support wasn't there.

One example is COM interop: COM is actually a semi-dynamic object system. When you do COM interop, a lot of methods actually return a dynamic object, but because C# didn't support them, they were returned as System.Object and you had to cast them yourself, possibly catching exceptions on the way.

Another example is interacting with dynamically typed (or even untyped) data, such as JSON, CSV, HTML, schemaless XML, schemaless web services, schemaless databases (which are, after all, the new hotness). Today, you use strings for those. An XML API would look like

var doc = new XmlDocument("/path/to/file.xml");
var baz = doc.GetElement("foo").GetElement("qux");

and so on. But how about:

dynamic doc = new XmlDocument("/path/to/file.xml");
var baz = doc.foo.qux;

Doesn't that look nice?

A third example is reflection. Today, invocation of a method via reflection is done by passing a string to InvokeMember (or whatever the thing is called). Wouldn't it be nicer to, you know, just invoke the damn thing?

Then, there is generation of dynamic data (basically the opposite of the second example). Here's an example how to generate some dynamic XML:

dynamic doc = new XmlBuilder();
doc.articles(id=42, type="List", () => {
article(() => {
number(42);
title("blahblubb");});});

This is not nearly as beautiful as the equivalent Ruby, but it is the best I could come up with at such short notice :-)

And last but certainly not least, integration with a dynamically typed language. Whether that is JavaScript in a Silverlight application, a custom rules engine embedded in your business app or a DLR instance that you host in your CAD program/IDE/text editor.

What is the practical use of dynamic variable in C# 4.0?

You won't really be able to dynamically create the method - but you can get an implementation of IDynamicMetaObject (often by extending DynamicObject) to respond as if the method existed.

Uses:

  • Programming against COM objects with a weak API (e.g. office)
  • Calling into dynamic languages such as Ruby/Python
  • Potentially making "explorable" objects - imagine an XPath-like query but via a method/property calls e.g. document.RootElement.Person[5].Name["Attribute"]
  • No doubt many more we have yet to think of :)

can a C# 'dynamic' variable refer to a static type?

Sorry, C# dynamic does not support this usage directly. In order to call a class method in C#, you have to name the type in your source code directly. And to do that, you have to reference the assembly. dynamic doesn't change this.

dynamic does dispatch to class methods when necessary (such as when you have a dynamic argument), but even in those cases the limitation above stands.

If the target types provided an instance that you could put in a dynamic variable, then you'd be fine. If you provided such an instance you'd be fine. Alternatively, if you have your heart set on dynamic, you could write your own IDynamicMetaObjectProvider that wraps these class methods dynamically given a System.Type. That would be an instructive project if you want to learn about the DLR, at least.

dynamic or object in C#

If what you want is to return a value whose type is determined at run time, and not at compile time, you should return dynamic. This will allow you to use the object in all appropriate types without C# giving you a compile time error, and possibly saving yourself from a few casting runtime errors caused by improper casts of object into a specific type.

public dynamic GetAnything(DataType dataType)
{
switch(dataType)
{
case Integer:
return 1;
case Decimal:
return 1.0;
case Boolean:
return true;
case Text:
return "1";
}
}

This will allow you to do:

var result = GetAnything(DataType.Text) + 1;

Without having to perform an explicit cast.

This is no more dangerous than returning an object, as you would do:

var result = (int)GetAnythingAsObject(DataType.Text) + 1;

Which would cause a runtime cast exception since object is in fact a string. Where as with dynamic, this will work for all types that support the + operator.

You can read more about the difference between object and dynamic in this msdn article: http://blogs.msdn.com/b/csharpfaq/archive/2010/01/25/what-is-the-difference-between-dynamic-and-object-keywords.aspx

Note: dynamic requires .Net 4 and over

How's memory allocated for a dynamic variable .net 4.0?

A variable of type dynamic is effectively a variable of type object as far as the CLR is concerned. It only affects the compiler, which makes any operations using a dynamic expression go through execution-time binding.

That binding process itself will use extra local variables etc (take a look in ILDASM, Reflector or something similar and you'll be staggered) but in terms of dynamicVar itself, the code you've got is just like having an object variable - with appropriate boxing for the int and bool values.

Anonymous Type vs Dynamic Type

An anonymous type is a real, compiler-generated type that is created for you. The good thing about this is that the compiler can re-use this type later for other operations that require it as it is a POCO.

My understanding of dynamic types is that they are late-bound, meaning that the CLR (or DLR) will evaluate the object at execution time and then use duck typing to allow or disallow member access to the object.

So I guess the difference is that anonymous types are true POCOs that the compiler can see but you can only use and dynamic types are late-bound dynamic objects.



Related Topics



Leave a reply



Submit