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?
Maybe it's just me, but I see dynamic
more as an convenient way to deal with COM interop and to interact with dynamic languages such as IronPython. dynamic
shouldn't really be used in an all-C# program.
Use a Dictionary<string, Component>.
And have a look at System.ComponentModel (i.e. the IContainer and IComponent interfaces).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With