Nice extention methods for Enums

I find  very nice Extention for enums  and i want to share it.

[Flags]
public enum ErrorTypes : int {
    None = 0,
    MissingPassword = 1,
    MissingUsername = 2,
    PasswordIncorrect = 4
}
 
public static class EnumExtensions {
 
    public T Append<T>(this System.Enum type, T value) {
        return (T)(object)(((int)(object)type | (int)(object)value));
    }
 
    public static T Remove<T>(this System.Enum type, T value) {
        return (T)(object)(((int)(object)type & ~(int)(object)value));
    }
 
    public static bool Has<T>(this System.Enum type, T value) {
        return (((int)(object)type & (int)(object)value) == (int)(object)value);
    }
 
}
 
...
 
//used like the following...
 
ErrorTypes error = ErrorTypes.None;
error = error.Append(ErrorTypes.MissingUsername);
error = error.Append(ErrorTypes.MissingPassword);
error = error.Remove(ErrorTypes.MissingUsername);
 
//then you can check using other methods
if (error.Has(ErrorTypes.MissingUsername)) {
    ...
}

http://stackoverflow.com/questions/9033/hidden-features-of-c/407325#407325

Advertisements

Define data type for enums

The data type can be defined for an enumeration:

enum EnumName : [byte, char, int16, int32, int64, uint16, uint32, uint64]
{
    A = 1,
    B = 2
}

Enum Inheritance

this is not possible. Enums cannot inherit from other enums. In fact all enums must actually inherit from System.Enum. C# allows syntax to change the underlying representation of the enum values which looks like inheritance, but in actuality they still inherit from System.enum.

See section 8.5.2 of the CLI spec for the full details. Relevant information from the spec

  • All enums must derive from System.Enum
  • Because of the above, all enums are value types and hence sealed

Source:
http://stackoverflow.com/questions/757684/enum-inheritance/757762#757762