Jump to content
  • Advertisement
Sign in to follow this  
Thevenin

Passing a 'Type' of type 'AbstractPotato'.

This topic is 3266 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

I have a class that takes in a variable of type 'Type'. It later casts the instance of this type to its respective type.

/* set during setup of the class */
public Type abstractpotatotype;



/* {much later in the code} */
AbstractPotato[] potato = new AbstractPotato[some_constant];
for(int x=0;x<some_constant;x++)
     potato[x] = (AbstractPotato)Activator.CreateInstance(abstractpotatotype);






The problem is, at compile time, I can set 'abstractpotatotype' to whatever I want.
abstractpotatotype= typeof(Bitmap);
causing an exception to be thrown at runtime. Unfortuntly, the class must be passed only the typeof(), because it's designed to instantiate its own quantity of this type (aka, it's not known outside the class). What I want to be able to do is write..
Type:AbstractPotato potatotype;
.. so that when I'm passing the type, the compiler knows that I'm passing it a type of Potato and not an image (even if it's an image of a potato). Is there a way I can enforce (at compile time) the type of the object that is passed without first instantiating it? [Edited by - jpetrie on October 15, 2009 2:06:43 PM]

Share this post


Link to post
Share on other sites
Advertisement
(You didn't specify a language, but...) With C# generics you can specify a base class, interface or other constraints on template arguments.

http://msdn.microsoft.com/en-us/library/d5x73970%28VS.80%29.aspx

That MAY help - but I'd warn that if you start having to rely this too much it might indicate a problem with your design that can be solved in a simpler way.

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!