Shane
Shane

Reputation: 1230

Am I misusing C# generics?

I tend to rely heavily on generics, but I'm worried I'm misusing them.

For example, I have an Entity that contains a dictionary of subclasses of Component, the type of the component being the key, the component being the value. Examples would be a PositionComponent, ColorComponent, etc.

I have methods for detaching and getting components, defined as such:

class Entity
{
    Dictionary<Type, Component> components;

    //...

    void DetachComponent<T>() 
        where T : Component 
    {
        components.Remove(typeof(T));
    }

    T GetComponent<T>()
        where T : Component
    {
        return (T)components[typeof(T)];
    }
}

The alternative I was debating using was simply making the functions use a parameter: void DetachComponent(Type componentType), but I didn't like calling each method like: entity.DetachComponent(typeof(ColorComponent));

Is this a misuse of generics? I generally do this for container classes, since key value pairs using the types as keys makes sense to me.

Upvotes: 4

Views: 248

Answers (1)

Heinzi
Heinzi

Reputation: 172260

I don't see anything wrong with it.

For DetachComponent, using generics is simply unnecessary -- you gain nothing from passing the type as a generic parameter instead of just passing a regular (Type componentType) parameter.

For GetComponent, using generics allows you to return the correct type at compile time without the calling code having to cast it. Here, using generics makes sense.

Since using generics

  • makes sense for GetComponent and
  • won't hurt for DetachComponent,

I think that for reasons of consistency it makes sense to use it for both (i.e., to do exactly what you have done).

Upvotes: 6

Related Questions