Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic vs Dictionary [C#]

Tags:

c#

dynamic

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?

like image 858
YellPika Avatar asked Dec 16 '22 19:12

YellPika


1 Answers

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).

like image 71
dtb Avatar answered Jan 02 '23 17:01

dtb