Best practices about creating a generic object dictionary in C#? Is this bad?
- by JimDaniel
For clarity I am using C# 3.5/Asp.Net MVC 2
Here is what I have done: I wanted the ability to add/remove functionality to an object at run-time. So I simply added a generic object dictionary to my class like this:
public Dictionary<int, object> Components { get; set; }
Then I can add/remove any kind of .Net object into this dictionary at run-time. To insert an object I do something like this:
var tag = new Tag();
myObject.Components.Add((int)Types.Components.Tag, tag);
Then to retrieve I just do this:
if(myObject.Components.ContainsKey((int)Types.Components.Tag))
{
var tag = myObject.Components[(int)Types.Components.Tag] as Tag;
if(tag != null) { //do stuff }
}
Somehow I feel sneaky doing this. It works okay, but I am wondering what you guys think about it as a best practice.
Thanks for your input, Daniel