Skip to main content
gamedev.net
🔒 Locked

Checking TYPE in c#?

Started by FxMazter 2 replies 400+ views
Original Post
FxMazter
FxMazter
I'm stuck with a problem in C#. I got something like this: class SomeClass<SupportedType> { bool IsSupported<TestType>() { //I want to check if SupportedType is derived from TestType //without creating an instance neither of them. //The test must be done within this function... //though helper functions may be used. } } In c++ I could even make this during compiletime with some templates, but I'm not sure how to do this in c# since generics don't work exactly as templates... Thank you for any advice!
joelmartinez
joelmartinez
I'm thinking you'll want to use type constraints ... so something like this:

class SomeClass<SupportedType> where SupportedType : TestType, new() {}


Not sure whether you can only constrain interfaces, or if you can do inheritance chains, but it looks right ;-)
Joel Martinez
http://codecube.net
[twitter]joelmartinez[/twitter]
snk_kid
snk_kid
namespace ConsoleApplication1{    class foobar<bar_type> {        public bool is_subtype<derived_type>()        {            return (typeof(bar_type)).IsSubclassOf(typeof(derived_type));        }    }    class foo { }    class bar : foo { }    class Program    {        static void Main(string[] args)        {            foobar<bar> f = new foobar<bar>();            Console.WriteLine(f.is_subtype<foo>());        }    }}


EDIT: as already mentioned type constraints are probably what you want, and yes you can constrain it to a type that implement particular interfaces.
FxMazter
FxMazter
Well, constraints are actually not what I want since I have an
interface something like this:

interface IFactoryCreator {
bool Create<ReturnType>(out ReturnType obj);
}

class FactoryCreator<CreateType> : IFactoryCreator {

bool Create<ReturnType>(out ReturnType obj) {
//if(CreateType is derived from ReturnType) then create the object
//else return false...
}

}


If I would to use a constraint, then the IFactoryCreator would need
to be a Generic class... which would bad for putting in a container right?

Or is there any other nice way that I'm not aware of?

Thank you!

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.