Easier Enums

Here's a slightly easier way to work with flag enumerations.

Consider this simple enumeration:

    /// <summary>
    /// Options enumeration used to specify behaviour when calling MakeHandledServiceCall()
    /// </summary>
    [Flags]
    public enum CallOptions
    {
        /// <summary>
        /// No special handling
        /// </summary>
        None = 0,
 
        /// <summary>
        /// Display validation messages to the user automatically
        /// </summary>
        ShowValidation = 1,
 
        /// <summary>
        /// Display exception messages to the user automatically
        /// </summary>
        ShowExceptions = 2
    }

Normally, to check if a particular option has been supplied, you need to write a clumsy test:

    if ((options & CallOptions.ShowValidation) == CallOptions.ShowValidation)
    {
        // Something
    }

Historically, this is what we've been stuck with - even in C# 2.0, because you can't constrain a generic method to work with enumerations.

However, with Extension methods in C# 3.0, we can write a helper like this:

    /// <summary>
    /// Test to see if the specified value includes a requested option
    /// </summary>
    /// <param name="aValue">Value to test</param>
    /// <param name="aOption">Option to test for</param>
    /// <returns>True of Value includes Option; false otherwise.</returns>
    public static bool Includes(this CallOptions aValue, CallOptions aOption)
    {
        return (aValue & aOption) == aOption;
    }

Which makes the test much easier to read:

    if (options.Includes(CallOptions.ShowValidation))
    {
        // Something
    }

Hope you find this useful!