How to use enums in Interfaces?

1.2k Views Asked by At

So we have Order which is Logic and IOrderData which connects the View and the Logic when it comes to data like properties. Order has properties of enums PayMethod and OrderStatus. How do I make properties of PayMethod and OrderStatus in IOrderData without the interface-layer knowing either Logic nor View?

Example:

Project Logic:

public class Order : IOrder, IOrderData
{
    public enum PayMethod
    {
        iDeal,
        creditcard,
        PayPal
    }

    public enum OrderStatus
    {
        NotPaid,
        InTheMaking,
        Shipped,
        Delivered,
        Confirmed
    }

public OrderStatus Status { get; set; }
public PayMethod Paymethod { get; set; }

Project DataInterface:

public interface IOrderData
{
    public OrderStatus Status { get; set; } //doesn't work
    public PayMethod Paymethod { get; set; } //doesn't work
}

My solution: I just made a new Class Library for Enums with classes of PayMethod and OrderStatus and everywhere where enums we're used I referred to the Class Library.

3

There are 3 best solutions below

7
Zohar Peled On

This code doesn't compile because your enums are members of the Order class. If you move them outside the class and make them top-level members of your namespace, as stated in official documentation:

Usually it is best to define an enum directly within a namespace so that all classes in the namespace can access it with equal convenience. However, an enum can also be nested within a class or struct.

This will solve the problem:

public enum PayMethod
{
    iDeal,
    creditcard,
    PayPal
}

public enum OrderStatus
{
    NotPaid,
    InTheMaking,
    Shipped,
    Delivered,
    Confirmed
}
public interface IOrderData
{
    OrderStatus Status { get; set; } 
    PayMethod Paymethod { get; set; }
}
public class Order : IOrder, IOrderData
{

public OrderStatus Status { get; set; }
public PayMethod Paymethod { get; set; }
0
Joelius On

Your enums are subtypes to Order therefore you have to fully qualify the name with Order. like so:

public interface IOrderData
{
    Order.OrderStatus Status { get; set; }
    Order.PayMethod Paymethod { get; set; }
}

Also public doesn't work for interface-members in C# 7.3 and below (see this question for C# 8+).

Alternatively, you can move the enums outside of the Order class like described in this other answer.

0
Cid On

Move the declaration of the enums outside of the class declaration, otherwise the interface won't know anything about that enum.

public enum PayMethod
{
    iDeal,
    creditcard,
    PayPal
}

public enum OrderStatus
{
    NotPaid,
    InTheMaking,
    Shipped,
    Delivered,
    Confirmed
}

public class Order : IOrderData
{
    public OrderStatus Status { get; set; }
    public PayMethod Paymethod { get; set; }
}

public interface IOrderData
{
    OrderStatus Status { get; set; }
    PayMethod Paymethod { get; set; }
}