8

I have learned and checked the advantages of dynamic keyword in C# 4.

Can any body tell me the disadvantages of this. Means dynamic vs Var/Object/reflection ???

Which thing is batter more. Is dynamic more powerful at run time??

akjoshi
  • 15,374
  • 13
  • 103
  • 121
Waheed
  • 10,086
  • 20
  • 53
  • 66
  • 3
    Var/reflection is not correct. Var is implicit typed variable evaluated at compile time. Reflection on the other hand is run time evaluated. I think reflection will stand more on side with dynamic than var. – Pawan Mishra Nov 20 '11 at 17:43
  • We can't really tell that what you know is sufficient without you telling us what you know. What are the advantages? Please add this info to the question. – Merlyn Morgan-Graham Nov 20 '11 at 17:45

2 Answers2

14

One of the most interesting thing with dynamic keyword which you can do is : implementation of multiple-dispatch.

Here is an example of double-dispatch (a specific case of multiple-dispatch). In OOP, at runtime a particular implementation of virtual (or abstract) method is called, based on the runtime type of one object which is passed as this to the member function. That is called single-dispatch, as the dispatch depends on the runtime type of single object. In double-dispatch, it depends on the type of two objects.

Here is one example:

public abstract class Base {}
public class D1 : Base {}
public class D2 : Base {}
public class D3 : Base {}

public class Test
{
   public static void Main(string[] args)
   {
       Base b1 = new D1();
       Base b2 = new D2();

       Method(b1,b2); //calls 1
       Method(b2,b1); //calls 1: arguments swapped!
   }

   public static void Method(Base b1, Base b2) // #1
   {
        dynamic x = b1;
        dynamic y = b2;

        Method(x,y); // calls 2 or 3: double-dispatch - the magic happens here!

   }
   public static void Method(D1 d1, D2 d2) // #2
   {
       Console.WriteLine("(D1,D2)");
   }
   public static void Method(D2 d2, D1 d1) // #3: parameters swapped 
   {
       Console.WriteLine("(D2,D1)");
   }
}

Output:

(D1,D2)
(D2,D1)

That is, the actual method is selected at runtime, based on the runtime type of two objects, as opposed to one object.

Nawaz
  • 353,942
  • 115
  • 666
  • 851
1

Not exactly var vs dynamic but the following SO link discuss reflection vs dynamic. Check Out : dynamic vs Var/Object/reflection

Community
  • 1
  • 1
Pawan Mishra
  • 7,212
  • 5
  • 29
  • 39