How do I give enum another name in C#?

Asked 2 years ago, Updated 2 years ago, 33 views

With DLLs that I didn't make myself

[Flags]
enum Flags {
    Flag0,
    Flag1,
    Flag2,
}

When enum like this is defined, it's hard to use with Flag0 or Flag1, so I'd like to give a meaningful alias like Monday and Tuesday. What should I do?

c#

2022-09-30 17:26

1 Answers

You cannot add enumeration values to the original type.

Provide a constant class or

public static class NamedFlags
{
    public static readonly Flags Sunday = Flags.Flag0;
    public static readonly Flags Monday = Flags.Flag1;
    public static readonly Flags Tuesday = Flags.Flag2;
}

You will define different enumeration types and convert them to each other.

[Flags]
public enum NamedFlags
{
    Sunday=Flags.Flag0,
    Monday = Flags.Flag1,
    Tuesday = Flags.Flag2,
}

public static class NamedFlagsExtension
{
    public static NamedFlags ToNamedFlags (this Flags value)
        =>(NamedFlags) value;

    public static Flags ToFlags (this NamedFlags value)
        =>(Flags) value;
}

However, the latter method will not work properly unless the original enumeration value is recompiled.


2022-09-30 17:26

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.