Jeff Quito
Jeff Quito

Reputation: 29

Does a C# Generics class casting similar to Java Generics class casting exist?

The code below is what I use for a java program to cast a generic to a specific. I understand there is no wild cards in C# but was hoping somebody can point me in the right direction as how I can modify the code to be similar to java:

public <T extends GameComponent<?>>T getComponent(int id, Class<T> type){
    return type.cast(components.get(id));
}

Upvotes: 2

Views: 111

Answers (1)

YoryeNathan
YoryeNathan

Reputation: 14522

Looks as something like:

public T GetComponent<T>(int id) where T : GameComponent
{
    return components[id] as T;
}

Thanks for everyone in the comments, helping me fix my solution (as I was way off). I couldn't have been here without you guys. And I'll miss you.

<3

But really, thanks :D

Upvotes: 4

Related Questions