You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Add Enum.SetFlag and Enum.RemoveFlag to make bitwise flagging easier #14084
To maintain multiple bool states in a class, instead of declaring many bool fields, an enum flag can be used to compact these states in to a single member to optimize for memory usage.
It is simple to test if a flag is set using Enum.HasFlag(DirtyFlags.X), but the scenario is not complete. Without the ability to set and remove a flag, the following code needs to be maintained manually:
// Setting a flagdirtyFlags|=DirtyFlags.X;// Removing a flag, this is harder to remember :(dirtyFlags&=^DirtyFlags.X;
The suggestion is to add 2 methods to Enum to help set and clear a flag.
publicboolHasFlag(Enumflag);// This method already existspublicboolSetFlag(Enumflag);publicboolRemoveFlag(Enumflag);
These methods should be aggressively inlined since bitwise manipulations is very likely to be used in a performance sensitive scenario.
Reacted by Joseph Musser, Keith Hall, Mikey, Fred James, Christoph Thiede, Amr, Joebu, Dinamytes, Ryder25, Maksym Koshovyi and 9 more
With the current language and runtime capabilities there's no way to implement SetFlag and RemoveFlag efficiently. Even the existing HasFlag has horrible performance compared to the "manual" way of testing flags.
@yufeih enum is now implemented in, well, not nice way. It's half-struct half-class which can turn out be any type in practice, and framework uses tons of hacks and quirks to make it work like it should.
So @mikedn is probably right - it will be hard to make it work fast.
However, it's probably worth trying.
UPD: Okay, looked at it for a bit more... I believe not much can be done here without changing specifications for enum. Now, argument for HasFlags is treated as object, so it requires boxing-unboxing and has corresponding performance hit.
It will not work fast without some serious changes in how enums work (generics?) but that will probably require changes at runtime and/or compilers.
@HellBrick Even with the enum constraint the problem is that the underlying type could be anything from sbyte to ulong and the IL for the bitwise math would have to be different for each of those types.
Some of this came up on the CodePlex Roslyn forums when I proposed supporting an enum constraint for C# generics with support for | and &.
sbyte to ulong and the IL for the bitwise math would have to be different for each of those types
As I explained before, the bitwise operations themselves are fine. The problem is with conversions that are needed in certain cases. That's something that could probably be fixed in the runtime, at least in the specific case of enums.
With the current language and runtime capabilities there's no way to implement SetFlag and RemoveFlag efficiently. Even the existing HasFlag has horrible performance compared to the "manual" way of testing flags.
I agree with this with why I believe we shouldn't add these APIs.
I can see how HasFlags is implemented in a really inefficient way. These methods should not be added like that. Maybe some kind of JitIntrinsic from coreclr might help here?
If the effort is not worth the outcome, I am fine with leaving things as is.
@terrajobst, I agree that we don't want to simply add these APIs, but I would put this (efficient flags/bitwise operations) issue on our list of big ticket items that we would like to consider fixing as part of the "modern BCL" push.
I am not sure how enum constraint would help. The type system still needs to describe the size of the backing integral type to implement many of these operations efficiently. I think something like making enums extend Enum where T: integral type would be needed.
@terrajobst is there online documentation covering that fact (CLI supporting non-integral backing types for enums)? Not finding any obvious results with my Google-fu
is there online documentation covering that fact (CLI supporting non-integral backing types for enums)? Not finding any obvious results with my Google-fu
Hmm, didn't notice this comment before. There's no such enum, CLI supports only enums of integral type:
The symbols of an enum are represented by an underlying integer type: one of { bool, char, int8, unsigned int8, int16, unsigned int16, int32, unsigned int32, int64, unsigned int64, native int, unsigned native int }
The difference between what CLI supports and what C# supports is { bool, char, native int, native unsigned int }
public class Enum: ValueType
{
+public T SetFlag<T>(T flag, bool condition = true) where T:struct,Enum;+public T UnsetFlag<T>(T flag) where T:struct,Enum => SetFlag(flag, false);
}
Edit: @danmoseley, anything else needed before this api could be ready for review?
I wrote this as an extension recently while updating a wpf application that bound several checkboxes to a single flagged enum. This made the properties I bound to on my object model nice and symmetric.
e.g.
publicboolIsStolen{
get =>_flags.HasFlag(InventoryFlags.IsFromStolenSource);
set =>_flags=_flags.SetFlag(InventoryFlags.IsFromStolenSource,value);}
Unfortunately the implementation itself was super hideous.
What is the state of this now? Before I start yet another round of API suggestions for Enum.HasAnyFlag() et al.
Enum.HasFlag is now inlined without performance penalty and it makes code look better, imo. And as a bonus in DEBUG it comes with a type check. Set/Unset/Has/HasAny will also avoid endless castings to/from int as the compiler is not smart enough to do it automatically.
This is 6.5 years old. There should be a decision now if it will be added or dropped.
@jkotas, any concerns on adding additional APIs to System.Enum here. It sounds like there would be 1-3 APIs and there has been continued interest since the initial proposal 7 years ago.
The three core scenarios are "set", "clear", and "toggle". Which could be handled via a single API:
cc @stephentoub here, since as I recall in a previous issue, he argued against providing alternative syntactic sugar to do basic flags operations. Instead we should just make sure that the standard way of writing such things (which is not C# specific) is efficient. I have to say I agree. When I see one of these methods, I would wonder which one to use.
Apologies for overlooking the ping to me higher up.
We've closed other related proposals, e.g. #66261. @jkotas has also expressed an opinion similar to mine, e.g. #55455 (comment), and also highlighted that just doing the idiomatic bit operations are guaranteed to be efficient where such named methods aren't, e.g. #55455 (comment).
Reacted by Tanner Gooding, Jan Kotas and Dan Moseley
Activity
mikedn commentedon Feb 8, 2015
With the current language and runtime capabilities there's no way to implement SetFlag and RemoveFlag efficiently. Even the existing HasFlag has horrible performance compared to the "manual" way of testing flags.
Alexx999 commentedon Feb 9, 2015
@yufeih enum is now implemented in, well, not nice way. It's half-struct half-class which can turn out be any type in practice, and framework uses tons of hacks and quirks to make it work like it should.
So @mikedn is probably right - it will be hard to make it work fast.
However, it's probably worth trying.
UPD: Okay, looked at it for a bit more... I believe not much can be done here without changing specifications for enum. Now, argument for HasFlags is treated as object, so it requires boxing-unboxing and has corresponding performance hit.
It will not work fast without some serious changes in how enums work (generics?) but that will probably require changes at runtime and/or compilers.
HellBrick commentedon Feb 9, 2015
This is another example where enum constraint on a generic argument (dotnet/roslyn#262) would be useful. It would allow something like
HaloFour commentedon Feb 9, 2015
@HellBrick Even with the
enumconstraint the problem is that the underlying type could be anything fromsbytetoulongand the IL for the bitwise math would have to be different for each of those types.Some of this came up on the CodePlex Roslyn forums when I proposed supporting an
enumconstraint for C# generics with support for|and&.mikedn commentedon Feb 9, 2015
As I explained before, the bitwise operations themselves are fine. The problem is with conversions that are needed in certain cases. That's something that could probably be fixed in the runtime, at least in the specific case of enums.
terrajobst commentedon Jan 5, 2016
@mikedn
I agree with this with why I believe we shouldn't add these APIs.
@weshaggard @KrzysztofCwalina what are your thoughts?
yufeih commentedon Jan 5, 2016
I can see how
HasFlagsis implemented in a really inefficient way. These methods should not be added like that. Maybe some kind of JitIntrinsic from coreclr might help here?If the effort is not worth the outcome, I am fine with leaving things as is.
KrzysztofCwalina commentedon Jan 5, 2016
@terrajobst, I agree that we don't want to simply add these APIs, but I would put this (efficient flags/bitwise operations) issue on our list of big ticket items that we would like to consider fixing as part of the "modern BCL" push.
HaloFour commentedon Jan 5, 2016
It would make a lot more sense to wait until C# supported generic enum constraints:
dotnet/roslyn#262
KrzysztofCwalina commentedon Jan 5, 2016
I am not sure how enum constraint would help. The type system still needs to describe the size of the backing integral type to implement many of these operations efficiently. I think something like making enums extend Enum where T: integral type would be needed.
HaloFour commentedon Jan 5, 2016
@KrzysztofCwalina True. Not perfect, but wouldn't an unchecked cast to
ulongand then back to the enum type be more efficient than what we have today?terrajobst commentedon Jan 6, 2016
Not sure that would work in all cases either. What if the enum is backed by a double/float? C# doesn't support CLI does.
kornman00 commentedon Mar 6, 2016
@terrajobst is there online documentation covering that fact (CLI supporting non-integral backing types for enums)? Not finding any obvious results with my Google-fu
mikedn commentedon Mar 6, 2016
Hmm, didn't notice this comment before. There's no such enum, CLI supports only enums of integral type:
The difference between what CLI supports and what C# supports is { bool, char, native int, native unsigned int }
13 remaining items
danmoseley commentedon Aug 12, 2020
This isn't required to ship 5.0
adamsitnik commentedon Dec 9, 2020
@danmosemsft Is there any chance we could introduce this API in 6.0? I find myself implementing it in every project I use ;)
danmoseley commentedon Dec 9, 2020
@adamsitnik if you are passionate about it your next step would be to get to api-ready-for-review and represent at API review.
zgabi commentedon Dec 19, 2020
There should be a non-generic version of the SetFlag/WithFlags/RemoveFlags/WithoutFlags, too.
For example:
public static object SetFlag(Type enumType, object value, object flag)
Or with ref parameter.
Similar to the Parse/TryParse methods: #14083
mburbea commentedon Mar 21, 2021
I would propose the following api to solve this:
public class Enum: ValueType { +public T SetFlag<T>(T flag, bool condition = true) where T:struct,Enum; +public T UnsetFlag<T>(T flag) where T:struct,Enum => SetFlag(flag, false); }Edit: @danmoseley, anything else needed before this api could be ready for review?
I wrote this as an extension recently while updating a wpf application that bound several checkboxes to a single flagged enum. This made the properties I bound to on my object model nice and symmetric.
e.g.
Unfortunately the implementation itself was super hideous.
NN--- commentedon Mar 22, 2021
Another possible implementation: https://github.com/rsdn/CodeJam/blob/master/CodeJam.Main/EnumHelper.cs#L375
hopperpl commentedon Nov 18, 2021
What is the state of this now? Before I start yet another round of API suggestions for Enum.HasAnyFlag() et al.
Enum.HasFlag is now inlined without performance penalty and it makes code look better, imo. And as a bonus in DEBUG it comes with a type check. Set/Unset/Has/HasAny will also avoid endless castings to/from int as the compiler is not smart enough to do it automatically.
This is 6.5 years old. There should be a decision now if it will be added or dropped.
tannergooding commentedon Aug 22, 2022
@jkotas, any concerns on adding additional APIs to
System.Enumhere. It sounds like there would be 1-3 APIs and there has been continued interest since the initial proposal 7 years ago.The three core scenarios are "set", "clear", and "toggle". Which could be handled via a single API:
or a set of APIs:
names up for debate, as would be whether they are instance or static.
danmoseley commentedon Aug 22, 2022
cc @stephentoub here, since as I recall in a previous issue, he argued against providing alternative syntactic sugar to do basic flags operations. Instead we should just make sure that the standard way of writing such things (which is not C# specific) is efficient. I have to say I agree. When I see one of these methods, I would wonder which one to use.
Apologies for overlooking the ping to me higher up.
stephentoub commentedon Aug 22, 2022
We've closed other related proposals, e.g. #66261. @jkotas has also expressed an opinion similar to mine, e.g. #55455 (comment), and also highlighted that just doing the idiomatic bit operations are guaranteed to be efficient where such named methods aren't, e.g. #55455 (comment).
tannergooding commentedon Aug 22, 2022
Closing as per the comments above.