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!

Comments

blog comments powered by Disqus
Next Post
The word "Estimate"  12 Mar 2009
Prior Post
The Butler Did It  01 Mar 2009
Related Posts
Browsers and WSL  31 Mar 2024
Factory methods and functions  05 Mar 2023
Using Constructors  27 Feb 2023
An Inconvenient API  18 Feb 2023
Method Archetypes  11 Sep 2022
A bash puzzle, solved  02 Jul 2022
A bash puzzle  25 Jun 2022
Improve your troubleshooting by aggregating errors  11 Jun 2022
Improve your troubleshooting by wrapping errors  28 May 2022
Keep your promises  14 May 2022
Archives
March 2009
2009