Is it possible to restrict a type parameter to concrete implementations of an abstract class, if those implementations don\'t have default constructors?
For example, if
You can add the new()
constraint, which will require that the class not be abstract and have a default constructor.
public class ZooPen<T> where T : Animal
{
public ZooPen()
{
if (typeof(T).IsAbstract)
throw new ArgumentException(typeof(T).Name + " must be non abstract class");
}
}
Here is one way to accomplish what you're asking for.
abstract class Animal
{
readonly string Name;
Animal() { }
public Animal(string name) { Name = name; }
}
abstract class Animal<T> : Animal where T : Animal<T>
{
public Animal(string name) : base(name) { }
}
class Penguin : Animal<Penguin>
{
public Penguin() : base("Penguin") { }
}
class Chimpanzee : Animal<Chimpanzee>
{
public Chimpanzee() : base("Chimpanzee") { }
}
class ZooPen<T> where T : Animal<T>
{
}
class Example
{
void Usage()
{
var penguins = new ZooPen<Penguin>();
var chimps = new ZooPen<Chimpanzee>();
//this line will not compile
//var animals = new ZooPen<Animal>();
}
}
Anyone maintaining this code will probably be a bit confused, but it does exactly what you want.