Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I create interface for enums in C#

Tags:

c#

enums

Suppose I have two enums as follow:

namespace A
{
    public enum AE
    {
        AE_0,
        AE_1
    }
}

namespace B
{
    public enum BE
    {
        BE_0,
        BE_1
    }
}

I would like to use these two enums looks like one so that, in a function, we can use both F(AE) and F(BE) without defining two functions.

As far as I know, we can create an interface for two different classes so that if we assign the interface as a parameter, these two classes can be used.

Can I do the same for enum?

Thank you.

Edit: I raise the problem because I already have enum A in namespace A. Now I would like to add enum B in namespace B without touching anything in namespace A. However, in namespace A, I already have a function F with enum A as parameter. Now I would like to use function F with enum B in namespace B. I got an error because enum A and enum B cannot convert to each other. Thank you.

like image 694
Ben Avatar asked Oct 20 '25 17:10

Ben


2 Answers

No, you cannot, because an enum inherits from System.Enum and nothing more.

Additionally, despite obvious appearances, applying an interface to an enum would not yield the desired results, since the enum members are implemented as static values, and an interface cannot specify static values.

Finally, if you have something that really should accept two kinds of enum parameters, consider whether they should be two separate enums, or a single enum with [Flags].

like image 59
David Avatar answered Oct 23 '25 05:10

David


Like others have mentioned, it might be best to use a generic method since C# doesn't let you create an interface for an enum. I've created a quick sample that let's you pass in members from different enumerations.

namespace A
{
    public enum AE
    {
        AE_0,
        AE_1
    }

    public class DoSomething
    {
        public static void F<T>(T enumMember) where T : struct
        {
            // exit early if something other than enum entered
            if (!typeof(T).IsEnum)
            {
                throw new ArgumentException("T is not enum");
            }

            // Do whatever you need to do here
            Console.WriteLine(enumMember.ToString());
        }
    }
}

namespace B
{
    public enum BE
    {
        BE_0,
        BE_1
    }
}

namespace C
{
    public class Class1
    {
        public static void processEnum()
        {
            A.DoSomething.F<A.AE>(A.AE.AE_0);
            A.DoSomething.F<B.BE>(B.BE.BE_0);
        }
    }
}
like image 31
shoefly Avatar answered Oct 23 '25 06:10

shoefly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!