7

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))
ValidfroM
  • 2,626
  • 3
  • 30
  • 41
  • If we could see more of what the other class does, we might be able to provide more relevant advice. – Kendall Frey Aug 24 '12 at 17:10
  • what is the type of `d`? if it is the right type can you not just call MyMethod on it without bothering to pass the type parameter (eg `d.MyMethod()`)? – Chris Aug 24 '12 at 17:11
  • 1
    @Chris The method is generic and takes no arguments. You can't omit the generic type parameter in this case because there is no way to infer it from usage. – Chris Hannon Aug 24 '12 at 17:33
  • @ChrisHannon: Ah yes, my bad. :) Forgot that it coudln't use return type to determine anything. :) – Chris Aug 28 '12 at 08:48

2 Answers2

7

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>();

    // ...
}
Dan
  • 9,717
  • 4
  • 47
  • 65
1

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?

Community
  • 1
  • 1
CodingGorilla
  • 19,612
  • 4
  • 45
  • 65
  • Surely you can make runtime decisions as long as you tell the compiler what the decisions are. If you cast to AObject explicitly then the compiler will know its an AObject and can work appropriately. – Chris Aug 24 '12 at 17:12
  • @Chris How do you do casting on a generic parameter? – CodingGorilla Aug 24 '12 at 17:14
  • @Chris The problem here is AObject is a base class. The T can be a AObject's derived class, no idea how to cast it. – ValidfroM Aug 24 '12 at 17:27
  • @ValidfroM You can't cast a generic parameter, so if Dan's answer doesn't work for you, then you'll have to use reflection. – CodingGorilla Aug 24 '12 at 17:29