Passing a 'Type' of type 'AbstractPotato'.

Started by
1 comment, last by Thevenin 14 years, 6 months ago
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]
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.

Visit http://www.mugsgames.com

Stroids, a retro style mini-game for Windows PC. http://barryskellern.itch.io/stroids

Mugs Games on Twitter: [twitter]MugsGames[/twitter] and Facebook: www.facebook.com/mugsgames

Me on Twitter [twitter]BarrySkellern[/twitter]

Ok, that works. Thanks. [grin]!

This topic is closed to new replies.

Advertisement