Home > Mobile >  List<> property able to have different types that all inherit from the same class
List<> property able to have different types that all inherit from the same class

Time:05-31

So I have for example this class

    public abstract class Feature
    {
        public string Id { get; set; }
        public string Type { get; set; }
    }

Then I will have different classes that all inherit this but are in other ways different

so for one example I will have this one

public class FirstClass: Feature
{
    public string FirstClassKey { get; set; }
}

And then i have another class that will have a List<> that I want to have the FirstClassKey and all Feature properties in it but it needs to be generic since if I have a similar SecondClass that also will inherit Feature class I want to be able to use the below class for a List that will have SecondClassKey and then all of Feature properties.

public class FeatureCollection
{
  public string Type { get; set; }
  public List<> Features { get;set; }
}

So sometimes a FeatureCollection object will look like

{
 Type: "SomeType",
 Features = [FirstClassKey: "12", Id: "20", Type: "FeatureType"]
}

And sometimes like

{
 Type: "SomeType",
 Features = [SecondClassKey: "48", Id: "20", Type: "FeatureType"]
}

Is this possible or will i have to create a FeatureCollection class for each of the different classes that will inherit the Feature abstract class

CodePudding user response:

I'm not sure I understand correctly what you want to accomplish, but it seems to me you want to make the FeatureCollection generic:

public class FeatureCollection<TFeature> where TFeature : Feature
{
  public string Type { get; set; }
  public List<TFeature> Features { get; set; }
}

Now FeatureCollection<FirstClass> can only store instances of FirstClass or instances of types that derive from FirstClass, while FeatureCollection<SecondClass> can't store FirstClass, but can store SecondClass...

  • Related