advantage of using dynamic type in c#

.net, c#

Solution

Dynamic type is useful for interoperability with other languages or frameworks like python,javascript.

Without dynamic you have to rely on reflection to get the type of the object and to access its properties and methods. The syntax is sometimes hard to read and consequently the code is hard to maintain. Using dynamic here might be much easier and more convenient than reflection.

Anders Hejlsberg gave a great example at PDC08 that looks like this:

object calc = GetCalculator();
Type calcType = calc.GetType();
object res = calcType.InvokeMember(
  "Add", BindingFlags.InvokeMethod, 
  null, new object[] { 10, 20 });
int sum = Convert.ToInt32(res);

The function returns a calculator, but the system doesn’t know the exact type of this calculator object at compile time. The only thing the code relies on is that this object should have the Add method.

With the dynamic keyword, this code looks as simple as this one:

dynamic calc = GetCalculator();
int sum = calc.Add(10, 20);

Reflection Vs Dynamic

Understanding the Dynamic Keyword

Problem

For example, if instance method `exampleMethod1` has only one parameter, the compiler recognizes that the first call to the method, ec. `exampleMethod1(20, 4)`, is not valid because it contains two arguments. The call causes a compiler error. The second call to the method, `dynamic_ec.exampleMethod1(10, 4)`, is not checked by the compiler because the type of `dynamic_ec` is dynamic. Therefore, no compiler error is reported. So what is the difference between compile time checking and run time checking and advantage of using dynamic type?

Original source