[SOLVED] Dynamic property type based on value of anther property

Issue

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?

Solution

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;
        }

    }
}

Answered By – Marius

Answer Checked By – Dawn Plyler (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *