views:

131

answers:

2

Usually I Use interfaces or base classes as paramter types when passing derived objects to a method. For example

Method1(ICar car);
Method2(BaseClass derivedClass);

But what about a Generic base class when the descendant class isn't generic ?

public class GenericBaseClass<T> where T : BaseClass
{}

public class GenericDerivedClass1 : GenericBaseClass<DerivedClass1>
{}

I can write something like

Method3(GenericBaseClass<BaseClass> class);

but I can't pass to this method am object of type GenericDerivedClass1.

Is there any way how to pass my descendant class to this method ?

+5  A: 

You need to make your Method3 generic:

private void Method3<T>(GenericBaseClass<T> baseClass)
{

}

and then you can call it like this:

Method3(new GenericDerivedClass1());
BFree
+1  A: 

One solution is to use non-generic base class for your generics:

abstract class GenericBaseClass
{
}

public class GenericDerivedClass1<T> : GenericBaseClass where T : DerivedClass1
{
}

Another solution is to use intefaces as pointed out in this article.

Li0liQ