Skip to content

[API Proposal]: Interlocked.Or/And for enums #114568

Open
@MihaZupan

Description

@MihaZupan

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&regexp=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

Debug.Assert(sizeof(Flags) == sizeof(ulong));
Interlocked.Or(ref Unsafe.As<Flags, ulong>(ref _flags), (ulong)flags);

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionEarly API idea and discussion, it is NOT ready for implementationarea-System.ThreadinguntriagedNew issue has not been triaged by the area owner

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions