Dynamic

Dynamic keyword in C#

Tuba Mansoor
Latest posts by Tuba Mansoor (see all)

There are two kinds of languages – Static(C#, Java) and Dynamic (Ruby, Javascript & Python).

In static the types are checked before execution, and in dynamic it is checked after execution.

C# is primarily a static language, but in .NET 4 dynamic features were introduced to provide more flexibility for things that earlier used reflection. DLR (Dynamic Language Runtime) was added to deal with this.

 class Program
    {
        static void Main(string[] args)
        {
            dynamic d = "test";
            d = 10;
            Console.WriteLine("Hello World!");
        }
    }

Look at the above piece of code. We can write the above code and C# will not throw an error. If we debug the code, we will find that the type of d is earlier set as a string which is later changed to int.

See also  Kafka Certification One Shot

But let’s do something like this.

class Program
    {
        static void Main(string[] args)
        {
            dynamic d = "test";
            d++;
            //d = 10;
            //Console.WriteLine("Hello World!");
        }
    }

This will not throw a compile-time error, but it will throw a runtime error.

Difference between var and dynamic?

var is used when you don’t want to define a type and let the compiler decide it for you. For example in the following piece of code, var will be defined as a string during compile time itself.

var x = "this is string";

What about cases in which both dynamic and var are mixed like in the below example?

 class Program
    {
        static void Main(string[] args)
        {
            dynamic d1 = 10;
            dynamic d2 = 5;
            var v = d1 + d2;

        }
    }

In the above case, d1,d2 and v will be defined as dynamic during compile time and dynamic(int) during runtime.

Another advantage of using the dynamic keyword is that we don’t have to explicitly used ‘ConvertToInt32’ or ‘Convert.ToString()’ etc. When we assign a value to the dynamic, the conversion will happen automatically.

That’s all about using the dynamic keyword in C#!

Further Reading

https://visualstudiomagazine.com/articles/2011/02/01/understanding-the-dynamic-keyword-in-c4.aspx

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types/using-type-dynamic