C# dynamic serves as a keyword utilized to introduce dynamism to properties or methods. By defining a dynamic type, the compiler defers validation to runtime instead of compile-time.
The primary reason for implementing dynamic binding is to circumvent the need for compile-time validation of the code.
The property established with the dynamic keyword functions similarly to an object. Dynamic variables are transformed into type object variables during compilation and are present solely during compilation, not during runtime.
Both dynamic and object types share similarities, which can be verified using the code snippet below.
C# Dynamic Binding Example 1
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
System.Int32
System.Int32
Now, let's modify both objects and observe the functional variance.
C# Dynamic Example 2
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, a compile-time error arises because of object v1. The dynamic object does not undergo compile-time checks, hence it does not generate any errors during compilation.
Output
DynamicExample.cs(13,18): error CS0019: Operator '+' cannot be applied to operands of type 'object' and 'int'
Dynamic Properties and Methods
In this instance, we are generating dynamic attributes and functions.
C# Dynamic Binding 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
Peter
Welcome to the hello world