Search code examples
c#type-safety

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


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


Solution

  • I decided to abandon this implementation. It smells bad to me.

    Instead I will accomplish what I need to do in a ViewModel class that lives in the application layer. The ViewModel will act as an aggregate for the domain model and all the other components that do not know about each other, but have a relationship under the domain model.