mao
mao

Reputation: 1404

Call generic method for subclass from generic method for superclass

I have two classes: Superclass and derived Subclass:Superclass. I have a generic method:

public void DoSmth<T>(T obj)
    where T : Superclass
{
    if(typeof(T).IsSubclassOf(typeof(Subclass))
    {
        DoSmth2<T>(obj);
    }
    //...
}

public void DoSmth2<T>(T obj)
    where T : Subclass
{ 
    //... 
}

As you see I want to call generic method for Subclass from generic method for Superclass. But compiler says that I can't do that:

The type 'T' cannot be used as type parameter 
'T' in the generic type or method 'DoSmth2<T>(T)'. 
There is no implicit reference conversion from 'T' to 'Subclass'

I use .Net 3.5. I understand that I can't do that just like I wrote above but is there any way to do that?

Upvotes: 1

Views: 2743

Answers (1)

Henk Holterman
Henk Holterman

Reputation: 273219

You can't but you don't have to either.

public void DoSmth<T>(T obj)
    where T : Superclass
{

   //untested but something like this
    Subclass obj2 = (obj as Subclass);   
    if(obj2 != null)
    {
        DoSmth2(obj2);
    }
    //...
}

Upvotes: 4

Related Questions