Vineeth S
Vineeth S

Reputation: 301

advantage of using dynamic type in c#

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?

Upvotes: 5

Views: 1703

Answers (2)

Anirudha
Anirudha

Reputation: 32817

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

Upvotes: 3

Tamir Vered
Tamir Vered

Reputation: 10287

You should use dynamic only when you dont care about performance (the search for the right method is done by reflection api whi h is realy slow) and when you dont care to risk for a runtime error. If you do want to use a dynamic call but dont want to risk your performance you can implement it youself using a cache from the argument types to the right method. There is a method for finding the right method ill edit when i refind it.

Upvotes: 0

Related Questions