We'll cover the following

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

It’s intuitive to use such operators with numeric types:

int sum = 4 + 7; // 11
int difference = 18 - 2; // 16
bool areEqual = sum == difference; // false


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

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

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

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;
}
}


We have a class, PreciousMetal. We need a functionality that will allow us to combine the property values of several precious metals. One way we could do that is by explicitly summing the properties:

var gold = new PreciousMetal(59.92m, 1);
var silver = new PreciousMetal(805.86m, 1000);
var combinedValue = gold.DollarValue + silver.DollarValue;
var combinedWeight = gold.Weight + silver.Weight;


A better approach would be to sum two PreciousMetal variables just like this:

var combined = gold + silver;


The combined variable contains both the combined weight and the combined dollar value. We can overload the + operator to make this possible:

public static PreciousMetal operator +(PreciousMetal operand1, PreciousMetal operand2)
{
// Contents
}


The syntax for overloading an operator is given above. Because + is a binary operator (it requires two operands), we must provide two parameters in the parentheses.

The following code playground demonstrates how the functionality is implemented:

Get hands-on with 1200+ tech skills courses.