So I have a container type generic object I'm using that looks like this:
public class Property<T>
{
T Value { get; set; }
}
I want to be able to do lists of Property of different generic types, so I did this:
public class Property
{
object BaseValue { get; set; }
}
public class Property<T> : Property
{
T Value { get; set; }
}
List<Property> properties = new List<Property>();
(Not shown is that BaseValue
and Value
both point to the same object, they'll always be the same). So now I can have collections of different types of properties. The problem I have now involves inheritance constraints. Say I have the following classes:
public abstract class Base { }
public class A : Base { }
public class B : Base { }
public class C { }
I want to be able to have a generic typed Property
class that constrains the type that goes in it, and that can be used as a generic parameter to other generics. Basically:
public List<Property<Base>> baseList = new List<Property<Base>>();
baseList.Add(new Property<A>()) //Works
baseList.Add(new Property<B>()) //Works
baseList.Add(new Property<C>()) //Won't work
However this doesn't work because even though A
inherits from Base
, Property<A>
does not inherit from Property<Base>
.
Is there some way to restructure these classes to allow that type of restraint? My current thought is making a new class something like:
public class PropertyBase<T> : Property<T> where T : Base { }
And using that, but 1) I'm not sure it would work, and 2) Even if it does, it would also create multiple classes that are functionally identical, but different types (Property<A>
and PropertyBase<A>
are pretty much the same functionally, but different types).