Imagine you have this enum definition and a variable of same type:
[Flags] public enum Tubo { One, Two } ... Tubo tubo = Tubo.One;
Now, how do you check if a variable of type Tubo contains a flag, i.e. Tubo.One? Simple, like this:
bool b = (tubo & Tubo.One) == Tubo.One;
But do you really like this notation? I mean it is a lot of typing and the expression is not clear at first sight. That's why I checked out if extension methods might help. So I created this experimental method:
public static bool Contains<T>(this T list, T flag) where T : struct { return (Convert.ToInt32(list) & Convert.ToInt32(flag)) == Convert.ToInt32(flag); }
And the new test would look like this:
bool b = tubo.Contains(Tubo.One);
Isn't this notation much more readable and easy to type? Sure. But there are two drawbacks in here:
- If a non-numeric structure is used the compiler won't catch the error (the restriction of generic type T is struct) – at the runtime you'll get casting error when the structure can't be converted to Int32.
- Performance. There is a monstrous performance hit, like 500x slower. There are many operations involved – mostly because of Convert.ToInt32 method usage. (extension method call is probably inlined). There is no other way since, as far as Contains method knows, the arguments are struct types, and struct types can't be used like numbers just like that.IOW this code won't work:
public static bool Contains<T>(this T list, T flag) where T : struct { return (int)list & (int)flag == (int)flag; }
But if the code above worked one would get a decent performance, not much slower than doing a simple bitwise and operation.
Unfortunately there is no better solution AFAIK. It would certainly help if we could restrict generic type T to enum (where T: enum).
Very nice! I love extension methods. Manipulation with Flags enum is one of the biggest inconvenience in .NET.
Do you know this trick which enables extension methods for NET 2.0? Awesome…
http://feeds.feedburner.com/~r/DidItWithDotNet/~3/189375492/C25.aspx
Hi Karel,
Yes, I knew that one. (I am subscribed to Dustin’s excellent blog)