Home > Blockchain >  Dynamic property type based on value of anther property
Dynamic property type based on value of anther property

Time:02-10

How to best implement a property with a dynamic data type depending on the value of another property?

I have a class for an Order with two properties OrderType (enum) and OrderStatus (enum)

The problem is that the data type for OrderStatus is different depending on the value OrderType

public class Order
{
    // Enums
    public enum OrderTypes { Restaurant, Grocery, Wallet }

    public enum RestaurantOrderStatus { OrderPlaced, Pending, Preparing, ReadyForPickup OnTheWay, Cancelled }
    public enum GroceryOrderStatus { OrderPlaced, Enqueued, Preparing, OnTheWay, Cancelled, Returning }
    public enum WalletOrderStatus { OrderPlaced, OnTheWay, Cancelled }

    // Properties
    public OrderTypes OrderType { get; set; }
    public OrderStatuses OrderStatus { get; set; } // How to set a dynamic data type (different enum)?
    public int Id { get; set; }
}

What is the best approach to do this?

CodePudding user response:

I would implement a Generic Type.

public class Order<T> where T : Enum
{
    public Enums.OrderTypes OrderType { get; set; }
    public T OrderStatus { get; set; }
    public int Id { get; set; }
}

public class Enums
{
    public enum OrderTypes { Restaurant, Grocery, Wallet }

    public enum RestaurantOrderStatus { OrderPlaced, Pending, Preparing, ReadyForPickup, OnTheWay, Cancelled }
    public enum GroceryOrderStatus { OrderPlaced, Enqueued, Preparing, OnTheWay, Cancelled, Returning }
    public enum WalletOrderStatus { OrderPlaced, OnTheWay, Cancelled }
}

public class UseCase
{
    public static void UseLike()
    {
        Enums.OrderTypes orderType = Enums.OrderTypes.Grocery;

        switch (orderType)
        {
            case Enums.OrderTypes.Restaurant:
                _ = new Order<Enums.RestaurantOrderStatus>();
                break;
            case Enums.OrderTypes.Grocery:
                _ = new Order<Enums.GroceryOrderStatus>();
                break;
            case Enums.OrderTypes.Wallet:
                _ = new Order<Enums.WalletOrderStatus>();
                break;
        }

    }
}

  • Related