Dynamic Binding

C# dynamic is a keyword that is used to make a property or a method dynamic. When we make dynamic type, compiler does not check it at compile-time. Compiler checks it only at run time.

The purpose of using dynamic binding is to avoid compile time checking of the code.

The property created using dynamic keyword works like object. Dynamic variables are compiled into type object variables and exist only at compile time, not at run time.

The type of dynamic and object both are similar. We can check it by using the following code.

C# Dynamic Binding Example 1

Example

using System;
namespace CSharpFeatures
{
    public class DynamicExample
    {
        public static void Main(string[] args)
        {
            dynamic v = 1;
            object v1 = 1;        
            Console.WriteLine(v.GetType());
            Console.WriteLine(v1.GetType());
        }
    }
}

Output

Output

System.Int32
System.Int32

Now, let's manipulate the both objects and see the working difference.

C# Dynamic Example 2

Example

using System;
namespace CSharpFeatures
{
    public class DynamicExample
    {
        public static void Main(string[] args)
        {
            dynamic v = 1;
            object v1 = 1;
            // Modifying Objects
            v  = v  + 3;
            v1 = v1 + 5;
            Console.WriteLine(v);
            Console.WriteLine(v1);
        }
    }
}

Now, it produces a compile-time error due to object v1. The dynamic object does not check at compile time so, it does not produce any error at compiler-time.

Output

Output

DynamicExample.cs(13,18): error CS0019: Operator '+' cannot be applied to operands of type 'object' and 'int'

Dynamic Properties and Methods

In the following example, we are creating dynamic properties and methods.

C# Dynamic Binding Example

Example

using System;
namespace CSharpFeatures
{
    public class Student
    {
        // Creating dynamic property
        public dynamic Name { get; set; }
        // Creating a dynamic method
        public dynamic ShowMSG(string msg)
        {
            return msg;
        }
    }
    public class DynamicExample
    {
        public static void Main(string[] args)
        {
            Student student = new Student();
            student.Name = "Peter";
            Console.WriteLine(student.Name);
            // Storing result in dynamic object
            dynamic msg = student.ShowMSG("Welcome to the hello world");
            Console.WriteLine(msg);
        }
    }
}

Output

Output

Peter
Welcome to the hello world

Input Required

This code uses input(). Please provide values below: