How can I rewrite this a generic?

Vaughan Hilts

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?

Scott Chamberlain

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.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

How can I rewrite URLs?

From Dev

How can I rewrite with apache mod_rewrite an entire directory?

From Dev

How can I rewrite this function with tail recursion

From Dev

How can I rewrite in a list in Erlang?

From Dev

How can I rewrite migration history on Django?

From Dev

How Can I Rewrite This More Efficiently

From Dev

How can I rewrite a subdomain to another subdomain?

From Dev

How can I rewrite this query to be more readable?

From Dev

How can I rewrite my controller URL?

From Dev

On cloudcontrol, how can I do a URL rewrite?

From Dev

How can i rewrite this code into a eventhandler

From Dev

How Can I Rewrite Without Stod()

From Dev

How can i rewrite URL in Nginx

From Dev

How can I register a generic object factory?

From Dev

How can I convert a generic list to an array?

From Dev

How can I define a generic extension method

From Dev

How can I create a generic setter for JTextField?

From Dev

How can I permute a generic list in Java?

From Dev

How can I compose generic methods in Scala?

From Dev

How can I make this Makefile more generic?

From Dev

How can I get the values of an "enum" in a generic?

From Dev

How can I get a generic type annotation

From Dev

How can I register a generic object factory?

From Dev

How can I create a generic setter for JTextField?

From Dev

How can I construct an EnumSet of generic varargs?

From Dev

How can I have a Generic method here?

From Dev

How can I pass generic type to generic methode?

From Dev

How can I extend a non generic interface into a generic one?

From Dev

How can I rewrite the native HTML input element with Polymer?