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
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 : Animal where T : Animal
{
public Animal(string name) : base(name) { }
}
class Penguin : Animal
{
public Penguin() : base("Penguin") { }
}
class Chimpanzee : Animal
{
public Chimpanzee() : base("Chimpanzee") { }
}
class ZooPen where T : Animal
{
}
class Example
{
void Usage()
{
var penguins = new ZooPen();
var chimps = new ZooPen();
//this line will not compile
//var animals = new ZooPen();
}
}
Anyone maintaining this code will probably be a bit confused, but it does exactly what you want.