Codectionary / Developer documentation / C#

Overload Operators for Value-Like Types

Give operators domain-appropriate meaning while keeping their behaviour unsurprising.

Read the syntax

Give operators domain-appropriate meaning while keeping their behaviour unsurprising.

Each component is added and used to construct the result.

What it is and why to use it

A small mathematical or measurement type can be easier to use when + or another operator expresses its natural operation. Operator overloading defines that behaviour for a user-defined type. Use it when the operator has an obvious meaning; a descriptive method is better when readers would need to guess what the symbol does.

How it works

The C# 12 examples declare public static operator methods with at least one operand of the containing type. The compiler resolves these overloads from operand types. Overloading + does not automatically implement equality, conversions or every related operator. Some operators must be supplied in pairs, such as == and !=. Newer language versions add further operator forms that these examples do not require.

Common mistakes and limitations

Do not make + unexpectedly mutate operands, perform remote I/O or change unrelated state. A valid signature does not ensure mathematically sensible semantics. When implementing equality operators, keep Equals and GetHashCode consistent as well.

Run the examples locally

These complete Program.cs examples use a .NET 10 console project with the C# language version set to 12.0, nullable checking enabled and implicit usings disabled. They use standard .NET libraries and need no extra NuGet packages. This is the verified environment, not a claim that every API requires .NET 10 or works unchanged in .NET Framework, Unity or other runtimes.

Install a supported .NET 10 SDK, create the console project, replace its project file with the settings below, then replace Program.cs with one complete example at a time. Build and run from the project folder. using directives bring namespaces into scope; top-level statements form the program’s entry point, and any helper types follow those statements. Console.WriteLine writes terminal output. Do not combine examples that declare the same type names.

C# in Codectionary’s Playground is editing-only: it does not compile or execute these programs. Run them with the local .NET SDK to reproduce the expected output. Async examples use controlled in-process operations rather than live network services or timing-sensitive delays.

Create and enter a project

dotnet new console -n CSharpExample --framework net10.0
cd CSharpExample

CSharpExample.csproj settings used for these examples

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <LangVersion>12.0</LangVersion>
    <Nullable>enable</Nullable>
    <ImplicitUsings>disable</ImplicitUsings>
  </PropertyGroup>
</Project>

Build and run after saving one example in Program.cs

dotnet build
dotnet run --no-build

Continue learning

Change one input and predict the result before running it. Follow the related guides to connect this topic with the surrounding language features.

Syntax

public static Point operator +(Point left, Point right) => new(left.X + right.X, left.Y + right.Y);

Examples

Add two small vectors

Return a new value without changing either input.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

var first = new Vector(2, 3);
var total = first + new Vector(4, 1);
Console.WriteLine($"{total.X}, {total.Y}");
Console.WriteLine($"{first.X}, {first.Y}");
readonly record struct Vector(int X, int Y) {
    public static Vector operator +(Vector a, Vector b) => new(a.X + b.X, a.Y + b.Y);
}
  1. The + expression calls the operator declared on Vector.
  2. Each component is added and used to construct the result.
  3. The first input retains 2, 3. The record struct supplies value semantics; this example adds only the component-wise addition rule.
  4. Expected output: 6, 4 2, 3
  5. Choose operators whose domain meaning is readily understood.

Scale a value with a scalar operand

Allow a vector multiplied by an integer while retaining a clear operand order.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

var result = new Vector(3, 2) * 4;
Console.WriteLine($"{result.X}, {result.Y}");
readonly record struct Vector(int X, int Y) {
    public static Vector operator *(Vector value, int factor) => new(value.X * factor, value.Y * factor);
}
  1. One operand is the containing Vector type, satisfying the operator rule.
  2. The integer factor multiplies each component to produce a new vector.
  3. This declaration supports vector * integer only; it does not automatically add integer * vector. Declare another overload if the domain needs that symmetry.
  4. Expected output: 12, 8
  5. Choose operators whose domain meaning is readily understood.

Best practices

  • Choose operators whose domain meaning is readily understood.
  • Prefer immutable results and consistent equality contracts for value-like types.

Runtime & versions

.NET runtime. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

C# language reference

Specifications & further reading