Say I have a class called Composite which contains a collection of another class Component, all of which have a property Name. Would it be better to use a Dictionary to store the components, or would it be better to use a dynamic object.
For example, would it be better to do this:
Component component = someComposite.Components["RandomComponent"];
or this:
Component component = someComposite.Components.RandomComponent;
Where someComposite.Components is dynamic in the second example.
The second case seems to be nicer, but there’s no type safety…
I want to add that at some point I will end up doing this:
DerivedComponent component = someComposite.Components["RandomComponent"] as DerivedComponent;
In which case dynamic can save me typing out the conversion.
So which is better design?
In a statically-typed language, those types are there for a reason; don’t just throw them out because of a little bit of extra syntax you have to put. That syntax is there as a warning — “Hey! I’m doing something that is not type-safe here!”
In the end, it all comes down to cost vs. benefits. You can either have the added benefit of type safety, static invocation, the IDE helping you when you refactor…or you can save yourself a tiny bit of typing (which is kind of like documentation).
Furthermore, you have to think about error conditions. With a
dynamic, your code on errors will look like this if the object does not contain that definition:Compared with:
That does not appear that you’re actually saving yourself that much typing.