Skip to content

[API Proposal]: UnionAttribute and IUnion interface #126650

@AlekseyTs

Description

@AlekseyTs

Background and motivation

As part of supporting Unions feature, we need:

  • a new attribute that will be used by C# compiler or by a C# developer to designate a Union type.
  • a new interface that will be implemented by compiler generated or user defined Union types.

API Proposal

namespace System.Runtime.CompilerServices
{
    [AttributeUsage(Class | Struct, AllowMultiple = false)]
    public class UnionAttribute : Attribute;

    public interface IUnion
    {
        // The value of the union or null
        object? Value { get; }
    }
}

API Usage

public union Pet(Cat, Dog){ ... }  // C# compiler generates a struct implementing IUnion with UnionAttribute on the struct
[Union] public struct Pet : IUnion // Developer manually declares a union type
{
    public Pet(Cat value) => Value = value;
    public Pet(Dog value) => Value = value;
    
    public object? Value { get; }
    
    ... 
}

Alternative Designs

No response

Risks

No response

Metadata

Metadata

Assignees

Labels

api-ready-for-reviewAPI is ready for review, it is NOT ready for implementationarea-System.Runtime.CompilerServicesblockingMarks issues that we want to fast track in order to unblock other important work

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions