ValidfroM
ValidfroM

Reputation: 2837

How to cast a generic Type to fit another generic method

I have a method in Class A

public IList<T> MyMethod<T>() where T:AObject

I want to invoke this method in another generic class B. This T is without any constraints.

public mehtodInClassB(){
    if (typeof(AObject)==typeof(T))
    {
      //Compile error here, how can I cast the T to a AObject Type
      //Get the MyMethod data
        A a = new A();
        a.MyMethod<T>();
    }
}

Class C is inherited from Class AObject.

B<C> b = new B<C>();
b.mehtodInClassB() 

any thoughts?

After urs reminding...Update:

Yes. What I actually want to do is

typeof(AObject).IsAssignableFrom(typeof(T))

not

typeof(AObject)==typeof(T))

Upvotes: 7

Views: 2062

Answers (2)

Dan
Dan

Reputation: 9837

If you know that T is an AObject, why not just provide AObject as the type parameter to MyMethod:

if (typeof(AObject).IsAssignableFrom(typeof(T)))
{
  //Compile error here, how can I cast the T to a AObject Type
  //Get the MyMethod data
    d.MyMethod<AObject>();
}

If providing AObject as a type parameter is not an option, you'll have to put the same constraint on T in the calling method:

void Caller<T>() where T: AObject
{
    // ...

    d.MyMethod<T>();

    // ...
}

Upvotes: 7

CodingGorilla
CodingGorilla

Reputation: 19842

You can't do that, unless you put the same constraint on the containing method. Generics are checked at compile time so you can't make runtime decisions like that.

Alternatively, you can use reflection to invoke the method, it just takes a little more code.

See this SO question for more info on how to do that: How do I use reflection to call a generic method?

Upvotes: 1

Related Questions