Best practices about creating a generic object dictionary in C#? Is this bad?

Posted by JimDaniel on Stack Overflow See other posts from Stack Overflow or by JimDaniel
Published on 2011-01-02T05:06:57Z Indexed on 2011/01/03 4:53 UTC
Read the original article Hit count: 226

Filed under:
|

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

© Stack Overflow or respective owner

Related posts about c#

Related posts about type-safety