Description
Background and motivation
#65184 made it possible to simplify code around Exchange
/CompareExchange
, but when dealing with enums you're still forced to use unsafe casts back and forth.
A few examples: https://grep.app/search?f.repo=dotnet%2Fruntime®exp=true&q=Interlocked%5C.%28%3F%3AOr%7CAnd%29%5C%28ref+Unsafe%5C.As
API Proposal
namespace System.Threading;
public static class Interlocked
{
// Existing naming:
// public static long Or(ref long location1, long value);
// public static T Exchange<T>(ref T location1, T value);
public static T Or<T>(ref T location1, T value) where T : struct, Enum;
public static T And<T>(ref T location1, T value) where T : struct, Enum;
}
API Usage
runtime/src/libraries/System.Private.Uri/src/System/Uri.cs
Lines 207 to 208 in 8f4365a
becomes
Interlocked.Or(ref _flags, flags);
Alternative Designs
Exchange
/CompareExchange
also have overloads for byte/sbyte/ushort/short.
Without the where T : Enum
constraint, we could make them "just work" with the generic overload. Otherwise we might want to add those overloads too at some point.
But not having it constrained would also bring in questions like whether float
/double
should be supported.
namespace System.Threading;
public static class Interlocked
{
public static T Or<T>(ref T location1, T value);
public static T And<T>(ref T location1, T value);
}
Risks
No response