C#C
C#10mo ago
T3M4CH

Get concrete generic type by Enum

Hello. Can someone explain how I can solve my problem. I have interface IContainerService<T>

public interface IContainerService<T> : IContainerBase where T : Product
{
    void AddProduct(T product);
    T GetProduct(int id);
}


and Entity from Database with Type(Box, Pallet, BigBox etc.) and T(ProductCategory : Food, Animals, Clothes)

public class Container
{
    public int Id { get; set; }
    public double MaxWeight { get; set; }
    public EContainerType Type { get; set; }
    public EProductType Category { get; set; }
}



And here's problem when I get my Container from DB Idk how to get concrete type and execute AddProduct method

I've tried something like this but with no results cause IContainerBase doesn't contains AddProduct just general method.
  public static IContainerBase CreateContainer(this Container container)
    {
        return (container.Type, container.Category) switch
        {
            (EContainerType.Box, EProductType.Animals) => new Box<Animals>(container.MaxWeight),

            (EContainerType.Box, EProductType.Food) => new Box<Food>(container.MaxWeight),

            (EContainerType.Box, EProductType.Clothes) => new Box<Clothes>(container.MaxWeight),

            (EContainerType.Pallet, EProductType.Animals) => new Pallet<Animals>(container.MaxWeight, 25.0),

            (EContainerType.Pallet, EProductType.Food) => new Pallet<Food>(container.MaxWeight, 25.0),

            (EContainerType.Pallet, EProductType.Clothes) => new Pallet<Clothes>(container.MaxWeight, 25.0),

            _ => throw new Exception("Bad container")
        };
    }


How can I get concrete type based by information from Enums? I want to get like method CreateContainer but with concreteType where I can call AddProduct and GetProduct method
Was this page helpful?