Jump to content
  • Advertisement
Sign in to follow this  
iliak

[.net] Good usage of generics ?

This topic is 3478 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi In my engine, I register generic asset providers like this : // Adds a provider AddProvider(Provider provider); // Removes a provider RemoveProvider(Provider provider) // List of providers in the engine List<Provider> Providers; To get a specific instance of a provider, here's how I'm doing :
public T GetProvider<T>()
{
	foreach (Provider provider in Providers)
	{
		if (provider is T)
			return (T)(object)provider; // <=== Here
	}

	return default(T);
}
Is the double cast a good method ???

Share this post


Link to post
Share on other sites
Advertisement
var providerAsT = provider as T;

this throw error CS0413 : The type parameter 'type parameter' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint

Share this post


Link to post
Share on other sites
You could add a class constraint, public T GetProvider<T>() where T : class

That said, in your case you probably want to constrain things even further with public T GetProvider<T>() where T : Provider

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!