I have a class hierarchy that looks like this:
class Base<TElement>
{
public TElement Element { get; set; }
}
class Concrete : Base<string>
{
}
I’d like to write a method that accepts Base subclasses:
public TConcrete DoSomething<TConcrete, TElement>()
where TConcrete : Base<TElement>
{
}
Is there any way to define DoSomething, without having to define TElement?
The ideal solution would be if the compiler could figure TElement automatically, so the calling code would look like this:
var item = DoSomething<Concrete>();
I’m using C# 4.0.
This is impossible for the following reasons:
where TConcrete : Base<???>.Here are a few workarounds.
Non-generic base type: Create a base class or interface type that is not generic. This is a common pattern; e.g.
IEnumerable<T> : IEnumerable.Covariant interface: With C# 4 generic interface covariance, you can create a type-safe solution that doesn’t require cluttering your types with “ugly” non-generic members:
And then:
And call it like: