Skip to content

Proposal: User-defined literals #4971

Closed
@alrz

Description

@alrz

Allows integer, floating-point, character, and string literals to produce objects of user-defined type by defining a user-defined suffix; providing a nice syntax for defining units of measure and domain-specific literals in a DDD context.
There is a similar feature in F# (MeasureAttribute) and (surprisingly) C++, but I really feel the need for this in C# as well.

As a regular operator:

class Distance {
    ...
    public static literal operator Distance km(double p) { ... }
}

As an extension operator (#4945):

public static literal operator TimeSpan hour(this double h) { ... }

Using improved type aliases (#4884):

// helps with further extension methods
using Radian = double;

// maybe in another file
public static literal operator Radian deg(double degree) { ... }

Usage:

Math.Sin(30deg);

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions