I am making some abstract base classes. The base object is defined as:
public abstract class Bar
{
public bool Enabled;
}
The base collection is defined as:
public abstract class Foo<T> : List<T>
where T : Bar
{
public Foo<T> GetAllEnabled()
{
Foo<T> ret = new Foo<T>();
foreach (T item in this)
{
if (item.Enabled)
{
ret.Add(item);
}
}
return ret;
}
}
Naturally, I get an error trying do create a new Foo<T>(), because Foo is an abstract class. Without the abstract modifier, everything works fine, but I want the modifier there because I want to make sure the class gets derived.
I have tried
Type U = this.GetType();
Foo ret = new U();
but I get an error "The type or namespace name 'U' could not be found (blah blah blah)".
I think my attempted fix should work, and I must just have the syntax wrong. What am I missing here?
Type Uwill contain information on the data type, it is not the equivalent of a generic type parameter that you can then instantiate. You can useUto create a type throughActivator.CreateInstance, which has a few overloads and acceptsTypeobjects, but then you’re left with needing to cast the resulting object to an appropriate type in order to be able to use it.