-2

I know the difference between Dynamic and Var in C#:

  • Dynamic: it uses reflection and late bound. (if you assign a wrong property, the build won't catch it until you run it.)
  • Var: it is early bound (if you assign a wrong property, the error automatically pops up when you do a build.)

But, I couldn't figure it out why would you need to use Dynamic over Var if Var is such a smart marker and knows about your intention by checking your assigned value.

I read a lot of articles but couldn't find the exact answer and my head is still spinning.

Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
M. Fawad Surosh
  • 450
  • 7
  • 20
  • 5
    You wouldn't use `dynamic` "over" `var`. They are very different features. `var` is just syntactic sugar that saves you typing out class names twice. `dynamic` is *not* for saving time typing, it's for variables whose type you can't know until runtime. – Blorgbeard Oct 10 '17 at 21:33

1 Answers1

2

Dynamic was primarily introduced for COM+ interopability where you where in situations where the types returned from the COM interface where not fixed. This can also be commonly seen in when interoping with other non typed languages like javascript (the code in the View in a ASP.NET MVC app is likely the most common place you will see it used).

Other than that most uses of dynamic you will see people use it for can be better handled by refactoring their code to provide a interface that represents a object.

Scott Chamberlain
  • 124,994
  • 33
  • 282
  • 431