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
Superpowers for your AI  29 Mar 2026
Autotitling Windows Terminal Tabs  17 Mar 2026
Don't assume shared understanding  25 Jan 2026
Better Table Tests in Go  21 Oct 2025
Error assertions  26 Apr 2025
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
Archives
March 2009
2009