When should one use dynamic keyword in c# 4.0?

33,233

Solution 1

Dynamic should be used only when not using it is painful. Like in MS Office libraries. In all other cases it should be avoided as compile type checking is beneficial. Following are the good situation of using dynamic.

  1. Calling javascript method from Silverlight.
  2. COM interop.
  3. Maybe reading Xml, Json without creating custom classes.

Solution 2

How about this? Something I've been looking for and was wondering why it was so hard to do without 'dynamic'.

interface ISomeData {}
class SomeActualData : ISomeData {}
class SomeOtherData : ISomeData {}

interface ISomeInterface
{
    void DoSomething(ISomeData data);
}

class SomeImplementation : ISomeInterface
{
    public void DoSomething(ISomeData data)
    {
        dynamic specificData = data;
        HandleThis( specificData );
    }
    private void HandleThis(SomeActualData data)
    { /* ... */ }
    private void HandleThis(SomeOtherData data)
    { /* ... */ }

}

You just have to maybe catch for the Runtime exception and handle how you want if you do not have an overloaded method that takes the concrete type.

Equivalent of not using dynamic will be:

    public void DoSomething(ISomeData data)
    {
        if(data is SomeActualData)
          HandleThis( (SomeActualData) data);
        else if(data is SomeOtherData)
          HandleThis( (SomeOtherData) data);
        ...
        else
         throw new SomeRuntimeException();
    }

Solution 3

As described in here dynamics can make poorly-designed external libraries easier to use: Microsoft provides the example of the Microsoft.Office.Interop.Excel assembly. And With dynamic, you can avoid a lot of annoying, explicit casting when using this assembly.

Also, In opposition to @user2415376 ,It is definitely not a way to handle Interfaces since we already have Polymorphism implemented from the beginning days of the language!
You can use

  ISomeData specificData = data;

instead of

dynamic specificData = data;

Plus it will make sure that you do not pass a wrong type of data object instead.

Solution 4

Check this blog post which talks about dynamic keywords in c#. Here is the gist:

The dynamic keyword is powerful indeed, it is irreplaceable when used with dynamic languages but can also be used for tricky situations while designing code where a statically typed object simply will not do.

Consider the drawbacks:

  1. There is no compile-time type checking, this means that unless you have 100% confidence in your unit tests (cough) you are running a risk.

  2. The dynamic keyword uses more CPU cycles than your old fashioned statically typed code due to the additional runtime overhead, if performance is important to your project (it normally is) don’t use dynamic.

  3. Common mistakes include returning anonymous types wrapped in the dynamic keyword in public methods. Anonymous types are specific to an assembly, returning them across assembly (via the public methods) will throw an error, even though simple testing will catch this, you now have a public method which you can use only from specific places and that’s just bad design.

  4. It’s a slippery slope, inexperienced developers itching to write something new and trying their best to avoid more classes (this is not necessarily limited to the inexperienced) will start using dynamic more and more if they see it in code, usually I would do a code analysis check for dynamic / add it in code review.

Solution 5

I will like to copy an excerpt from the code project post, which define that :

Why use dynamic?

In the statically typed world, dynamic gives developers a lot of rope to hang themselves with. When dealing with objects whose types can be known at compile time, you should avoid the dynamic keyword at all costs. Earlier, I said that my initial reaction was negative, so what changed my mind? To quote Margret Attwood, context is all. When statically typing, dynamic doesn't make a stitch of sense. If you are dealing with an unknown or dynamic type, it is often necessary to communicate with it through Reflection. Reflective code is not easy to read, and has all the pitfalls of the dynamic type above. In this context, dynamic makes a lot of sense.[More]

While Some of the characteristics of Dynamic keyword are:

  1. Dynamically typed - This means the type of variable declared is decided by the compiler at runtime time.
  2. No need to initialize at the time of declaration.

e.g.,

dynamic str; 

str=”I am a string”; //Works fine and compiles

str=2; //Works fine and compiles
  1. Errors are caught at runtime

  2. Intellisense is not available since the type and its related methods and properties can be known at run time only. [https://www.codeproject.com/Tips/460614/Difference-between-var-and-dynamic-in-Csharp]

Share:
33,233
ACP
Author by

ACP

Updated on May 04, 2020

Comments

  • ACP
    ACP about 4 years

    When should one use dynamic keyword in c# 4.0?.......Any good example with dynamic keyword in c# 4.0 that explains its usage....

  • KDecker
    KDecker almost 9 years
    I've been trying to do something like this for a few days, leaving it and coming back to it. This would work very well. So yes this, to me at least, seems very hard to do without dynamic.
  • nothingisnecessary
    nothingisnecessary over 7 years
    I like how you put "Maybe" for number 3. I would argue this is a weak "maybe" because usually an investment in defining reusable classes for business data structures pays off in the long term. So the "maybe" should perhaps be reserved for when you are rapidly prototyping a product and either don't have the time or are too lazy to define reusable custom business data types.
  • Ashkan S
    Ashkan S over 7 years
    OMG! use ISomeData specificData = data; instead of dynamic! Why would you use dynamic for such a simple task
  • gor
    gor over 7 years
    And what if ISomeData comes from another library and you can't add anything in it's source ? Or maybe you want to implement visitor pattern, to be able to add dynamically behavior to those objects ?
  • kan
    kan over 6 years
    I've added some clarification to @user2415376 answer what exactly happens when dynamic is used. Your suggestion to use polymorphism is incorrect.
  • Ashkan S
    Ashkan S over 6 years
    @kan your equivalent is not equivalent at all! you just need to call HandleThis( specificData ); without the casting it.
  • Ashkan S
    Ashkan S over 6 years
    @kan your understanding of polymorphism is wrong, therefore your clarification is also wrong. The "HandleThis" method should be implemented with the base class or the interface as the input. you have simply written a code that is not doing anything
  • kan
    kan over 6 years
    Nothing to do with polymorphism here, it is not applicable in this scenario. When specificData is of type ISomeData then code will not compile as compiler could not pick HandleThis method overloads. When specificData is of type dynamic - the compiler does nothing and overload is picked by run-time type. In other words - dynamic allows implementing en.wikipedia.org/wiki/Dynamic_dispatch too, not relying on polymorphism.
  • kan
    kan over 6 years
    This is another example of the code. Try to use polymorphism here: dotnetfiddle.net/Da9gIC
  • user2415376
    user2415376 over 6 years
    Wow.. didn't expect this post to get this much attention. :) But ya.. polymorphism isn't at play here. In order for that to work, you'd have to edit the ISomeInterface interface and add an entry for each implementation of ISomeData. Have you tried running this code and testing the polymorph idea? There is no way for the code inside SomeImplementation to know what to call via polymorphism. So what this does, is let you code some rule implementations maybe, where the rules engine might get updates as new structures come about.
  • user2415376
    user2415376 over 6 years
    Referring to my answer, with my comment, it is not polymorphism.. Not saying I'm using 'dynamic' all over.. in fact the 1 or maybe 2 times I've ever used it, I posted it here because it seemed odd to me.. but I was in a situation that I could not get out without it or doing some big heavy lifting in the rest of the code.
  • user2415376
    user2415376 over 6 years
    My goal was not to post "HEY GOOD WAY TO USE!" but just simply a usage. I strive not to use 'dynamic', only used it this 1 time, maybe 1 other somewhere. And I wrapped a bunch of try/catch around it in case it failed. It was not my desire to use it; it came out of necessity.
  • user2415376
    user2415376 over 6 years
    @AshkanSirous How then would you code this? And mind you, clearly this would not be a green field situation, but that there are other limitations in the code base at stake.
  • Ashkan S
    Ashkan S about 6 years
    @user2415376 thanks for elaboration. I understand what you mean and I really liked it. Thanks a lot
  • Ashkan S
    Ashkan S about 6 years
    @kan Thanks a lot for the example. It helped me to understand what problem you are addressing and more interestingly I've just used it in a code :D so thank you a lot
  • kan
    kan about 6 years
    @AshkanSirous Nice, thanks. I suggest you undo your edit on user2415376's answer to add back my remark then. BTW, this is quite heavy weapon, so do not use this ligthly on any occasion.
  • Ashkan S
    Ashkan S about 6 years
    @kan I understand that :D Also I've added a try catch around it, since we don't have many of compile time validations.
  • StayOnTarget
    StayOnTarget about 6 years
    I added below a specific COM interop example stackoverflow.com/a/50154066/3195477
  • Jansky
    Jansky about 6 years
  • Andrés Quiroz Valdovinos
    Andrés Quiroz Valdovinos about 4 years
    @user2415376 how can we differ your solution from using dynamic into using var?