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
The Liskov substitution principle goes both ways  21 Mar 2020
Avoid hardcoded wait times  26 May 2018
Guaranteed Progression  19 May 2018
Prefer declarative method names  03 Feb 2018
Using Premeditation  27 Jan 2018
With Relocation  20 Jan 2018
Using Consolidation  13 Jan 2018
Using Semantic Types  06 Jan 2018
Using Extension Methods  30 Dec 2017
Error Methods  25 Nov 2017
More smart-code posts »
Archives
March 2009
2009