Dynamic binding in C# is the process of resolving members, types, and operations from compile-time to run-time. This is useful at compile time when we know there is going to be particular function or member or operation, but the compiler does not know about it. This helps us when we are calling dynamic language like IronPython or COM object from C#. We can create dynamic type by using the dynamic keyword as shown below. Open Microsoft Visual Studio and create a console application.
class Program
{
static void Main(string[] args)
{
dynamic d = new Company();
d.GetEmployee();
}
}
public class Company
{
public void GetEmployee()
{
}
}
As shown above, we created dynamic type d for Company class using dynamic keyword. Here compiler does not know and it won’t care whether Company class has GetEmployee() method or not, at run-time only will get to know whether particular type exists or not. Since d is dynamic, the compiler defers binding GetEmployee() to d until run-time. Runtime produces an exception if GetEmployee() type is not available in Company class.
Differences between Static binding & Dynamic binding:
Let’s create an object for Company class by using the static binding as shown below.
static void Main(string[] args)
{
Company obj = new Company();
obj.GetEmployee();
}
As shown above, in static binding compiler searches for the parameter less GetEmployee() type in Company class. If the called type is not available, then compiler produces the error. That means in static binding; binding happens at compile time whereas in dynamic binding it occurs at runtime.
If we change the static type to object like below, the compiler produces an error even though GetEmployee() is available in Company class.
static void Main(string[] args)
{
object obj = new Company();
obj.GetEmployee();
}
This is because when you declare a class with the object, the only information available for object obj is just Company type and it does not know what available in Company class. The dynamic type also same as object type, but dynamic object binds at runtime based on its runtime type, not its compile-time type like object type. Dynamic object implements IDynamicMetaObjectProvider interface at runtime which is used to perform the binding.