Dynamic Type In C# 4.0

What is Dynamic Type in C#?

Dynamic is a new type introduced in c# 4.0. Dynamic types are declared with the dynamic keyword. The objects of type Dynamic are not type-checked at compile time. It behaves like a type Object in most cases. Objects of any type can be assigned to a variable of Dynamic type. Variable of Dynamic type can get its value even from HTML Document Object Model (DOM) or COM API. If the code is not valid, errors are caught at run time, not at compile time.

C# was, until now, a statically bound language. This means that if the compiler can't find the method for an object to bind to, then it will throw a compilation error.

We declare at compile-time the type to be dynamic, but at run-time, we get a strongly typed object.

Dynamic objects expose members such as properties and methods at run time instead of compile time. If you try to access members of a Dynamic type in Visual Studio IDE, you will get the message "The operation will be resolved at runtime;

dynamic object

Difference between Object, Var, and Dynamic type

The fundamental distinction between object, var, and dynamic types lies in their role and behavior within C# code. The object type is a universal container capable of holding any data type but requires explicit casting for access. In contrast, var is a compile-time feature that automatically infers the data type based on the initialization value, promoting concise and readable code with compile-time type safety. Lastly, dynamic defers type checking to runtime, permitting dynamic typing and flexibility but sacrificing compile-time safety.

If we execute the following code.

using System;

namespace VariableTypesExample
{
    class Program
    {
        static void Main(string[] args)
        {
            dynamic dyn = 0;
            object obj = 0;
            var var1 = 0;
            Console.WriteLine(dyn.GetType());
            Console.WriteLine(obj.GetType());
            Console.WriteLine(var1.GetType());
        }
    }
}

We will get the runtime types of all the Object, Dynamic, and var variables as Sytem.Int32 .But the type of var variable is available at compile time as well.

But now, if we add the following two statements, the second statement will give a compile time error because the expression is type-checked at compile time, while the first statement compiles successfully because expressions of dynamic type are not type-checked at compile time, and the var type variable is assigned the appropriate datatype at compile time itself.

using System;

namespace VariableManipulationExample
{
    class Program
    {
        static void Main(string[] args)
        {
            dynamic dyn = 0;
            object obj = 0;
            var var1 = 0;
            dyn = dyn + 1;
            obj = Convert.ToInt32(obj) + 1;
            var1 = var1 + 1;
            Console.WriteLine("Dynamic: " + dyn);
            Console.WriteLine("Object: " + obj);
            Console.WriteLine("Var: " + var1);
        }
    }
}

If we execute the below program.

using System;
using System.Text;
namespace DynamicExample
{
    class DynamicTest
    {
        static void Main(string[] args)
        {
            dynamic dyn;
            string str = "Dynamic type test. String";
            StringBuilder sb = new StringBuilder();
            sb.Append("Dynamic type test. StringBuilder");
            dyn = str;
            DynamicFunction(dyn); // This will call the first function because at runtime, the dynamic type is of string type
            dyn = sb;
            DynamicFunction(dyn); // This will call the second function because at runtime the dynamic type is of StringBuilder type
            Console.Read();
        }
        public static void DynamicFunction(string s)
        {
            Console.WriteLine(s);
        }
        public static void DynamicFunction(StringBuilder sb)
        {
            Console.WriteLine(sb.ToString());
        }
    }
}

We will get the output as shown below.

dynamic type

To conclude, Dynamic Type is a nice feature when it comes to interoperability and .NET usage with other Dynamic languages. However, Dynamic type also makes it the responsibility of the developer for the correct usage of the calls.


Similar Articles