This post is in continuation of this one.
I am trying to understand if I am the only one who misses and needs the ability of a .NET generic type to inherit one of it
The basic rule of generics that prevents this is "the content of a generic type must be well-defined on the generic argument." Lets look at how this applies to the following code:
public abstract class AbstractBase
{
public abstract string MyMethod();
}
public class SomeType : T
{
}
public class SomeUsage
{
void Foo()
{
// SomeType does not implement AbstractBase.MyMethod
SomeType b = new SomeType();
}
}
So we try to implement MyMethod():
public class SomeType : T
{
public override string MyMethod()
{
return "Some return value";
}
}
public class SomeUsage
{
void Foo()
{
// SomeType does not inherit a virtual method MyMethod()
SomeType b = new SomeType();
}
}
So lets make a requirement that T be derived from AbstractBase:
public abstract class DerivedAbstractBase : AbstractBase
{
public abstract string AnotherMethod();
}
public class SomeType : T
where T : AbstractBase
{
public override string MyMethod()
{
return "Some return value";
}
}
public class SomeUsage
{
void Foo()
{
// SomeType does not implement DerivedAbstractBase.AnotherMethod()
SomeType b = new SomeType();
}
}
By the time you account for all the restrictions in base types, you're so constrained that deriving from a generic parameter is pointless.