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

About bpostaci
Sr. Support Escalation Engineer in Microsoft.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: