Wednesday, April 13, 2011

Using Linq to build a complete value for a Flags Enum in C#

Sometimes its useful, when you have a Flags Enumeration to have amember that represents all the possible values, such as this example:

[Flags]
public enum MyEnum
{
Value1 = 1,
Value2 = 2,
Value3 = 4,
All = Value1 | Value2 | Value3
}

But what if if you don't have access to the source code and the enum declaration does not have such a member? It might be part of a library, for instance. You could do something like this:

static readonly MyEnum AllMyEnum = MyEnum.Value1 | MyEnum.Value2 | MyEnum.Value3;

But that has problems, since you've got a bug as soon as the Enum declaration is changed. It is in fact a violation of the DRY Principle, since the list of members of the enum is reapeated at two places. There is a clever solution using Linq though:

static readonly MyEnum AllMyEnum = Enum.GetValues(typeof(MyEnum )).OfType.Aggregate((current, next) => current| next);

What's happening here? We first use Enum.GetEnum to get an array with all the possible values for MyEnum. That right there slays the DRY dragon, since we retrieve the existent list of members rather than redefine it. To OR the list together we first cast it to an IEnumerable and then aggregate it. The Aggregate functions takes a delegate which tells it how to include a new value in the aggregation in process. The starting value for the aggregation is the default for the Type, which is just fine in this case.

I hope this little one-liner is useful for you as it was for me.

No comments:

Post a Comment