Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

operator: practical reference

operator: practical reference: operator declares an operator overload for a user-defined type.

Version: C# language; verified against C# 14 reference

Syntax

operator /* grammar-specific form */

operator declares an operator overload for a user-defined type.

Use it when the operation has natural mathematical or value semantics.

Surprising side effects break intuition; keep equality operators mutually consistent.

At least one operand must be the declaring type, and not every operator is overloadable.

The complete program actually uses operator; its exact expected stdout is 5.

Examples

using System;

var result = new Number(2) + new Number(3);
Console.WriteLine(result.Value);

readonly record struct Number(int Value)
{
    public static Number operator +(Number left, Number right) => new(left.Value + right.Value);
}

Result

5

The complete program actually uses `operator`; its exact expected stdout is `5`.

Sources