I have the following piece of code:
public Component GetComponent(Type type)
{
return Components.FirstOrDefault(component => component.GetType() == type);
}
The caller has to do a nasty cast to get the component it passed in - how can I rewrite this to a cast-less generic?
If I read your question correctly, you can move the cast inside the function and do it this way.
public T GetComponent<T>() where T : Component
{
return (T)Components.FirstOrDefault(c => c.GetType() == typeof(T));
}
If the type is not known at compile time going in to the function (like, say GetComponet()
is called in a loop where the type is passed in as a argument) there is no way to get a strongly typed object back.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments