Search⌘ K
AI Features

Operator Overloading

Explore operator overloading in C# to enhance your classes by defining custom behavior for arithmetic and comparison operators. Understand how to implement overload methods for user-defined types, enabling intuitive operations such as adding objects or comparing values, while maintaining code clarity and safety.

C# provides various operators for performing arithmetic and comparison. Some examples are +, -, >, and <.

Using these operators with numeric types is intuitive:

int sum = 4 + 7; // 11
int difference = 18 - 2; // 16
bool areEqual = sum == difference; // false
Standard arithmetic operations with integer types

To use these operators with user-defined types, we can overload them.

Overloading arithmetic operators

In C#, we can overload arithmetic operators (+, -, /, *, %).

Let’s first define a class that benefits from these overloads:

C# 14.0
namespace OperatorOverloading;
public class PreciousMetal
{
public decimal DollarValue { get; set; }
public decimal Weight { get; set; }
public decimal PricePerGram
{
get { return DollarValue / Weight; }
}
public PreciousMetal(decimal dollarValue, decimal weight)
{
this.DollarValue = dollarValue;
this.Weight = weight;
}
}
  • Line 1: We use a file-scoped namespace to organize the code without extra indentation.

  • Lines 5–6: These properties store the raw data for the metal.

  • Lines 8–11: A read-only property calculates the price per gram dynamically.

  • Lines 13–17: We define the constructor that accepts the initial value and weight. We assign the passed ...