Dynamic in C#1 min read

What are dynamic’s?

We have two type of languages: Static and Dynamic. Since C# is static language it is pretty cool to have type like dynamic included in it.
Static languages are the ones which resolutions are done during compile-time while Dynamic languages are the ones in which resolutions are done during run-time.
Dynamic types were added in .NET 4 version to make it easier to work with COM (office apps for instance) and to avoid Reflection as it is a bit complicated.

i.e.:

// using reflection

object foo = CustomObject;
var method = obj.GetType().GetMethod("NameOfMethod");
method.Invoke(null,null);

//using dynamic

dynamic foo = CustomObject;
foo.NameOfMethod();

As you can see in previous example, it is much cleaner and simpler to use dynamic than reflection.
Let’s look at another example:

dynamic foo = "bar";
foo = 10;

In this example we are not going to get exception, why? Because it’s a dynamic type!
We set foo variable as a type of string and then we tried to change it’s variable type to integer (hence number 10).
And during run-time, variable foo just changed it’s type to integer.
So, when using dynamic it is not necessary to cast to specific type.

i.e.:

int a = 10; // a if of type int
dynamic b = a; // b is of type int
long c = b; // c is of type long

SUMMARY:

It is pretty easy to use dynamic type and although i dont use it often, in some situations it is definitely a go to approach.

Leave a Reply

Your email address will not be published. Required fields are marked *