Skip to content

Operator Overloading

Become a developer with our complete learning paths
Become a developer with our complete learning paths

Welcome to a new C# tutorial!.

In this tutorial, we will learn about operator overloading. Although it sounds fancy, it’s pretty simple : ).

So what is operator overloading exactly ?.

The Problem

First, let’s look at the problem at hand.

Let’s say we have two numbers, a = 5 and b = 3 defined as ints.

If we want to add these two numbers, we can do something like this, int c = a + b;

int a = 5, b = 3;
int c = a + b;

But what if we have two objects of type Ticket.

Where each ticket has a duration and Id properties and maybe other properties like Creation Date etc.

Ticket ticket1 = new Ticket();
Ticket ticket2 = new Ticket();

Naturally, we can’t just add two tickets using the + operator, well because the compiler won’t know how to add these tickets exactly.

Ticket ticket3 = ticket1 + ticket2;

Like do we want to add the time of creation? do we need to create a new Id for the third ticket object?.

In our case when we add two tickets objects we want to have a third ticket object with its duration = ticket1.duration + ticket2.duration.

This is where operator overloading comes in handy.

The Solution

Operator overloading is The overloading of the built-in operators in C#.

It is the same overloading concept that we are familiar with but applied to operators instead.

Operator overloading will allow us to use the C# operators with our own classes and structs.

The Syntax to overload an operator will look like this.

public static return_type operator op (Type t)  
{  
    //operator logic 
}  

Since we will most likely use this overload from outside our class we will start by public static, this is because the operator methods are class methods and not object method.

Then we define the return type followed by the operator keyword.

Then we need to specify which operator we are overloading for example +, -, and finally the parameters of the operator.

Operator Overloading Example

For example, if we have a class called Car with a property called speed.

public static Car operator + (Car car1,Car car2)  
{  
    Car carSum = new Car();
    carSum.Speed = car1.Speed + car2.Speed;
    return carSum;
}  

Then we can overload the arithmetic operator + using the following code:

public static Car operator

We started with public static then the return type which is, in this case, is Car, then the + operator, Followed by two Car parameters which we are trying to add together.

As you can see it’s very simple, so let’s try it out in visual studio!.

Overriding the + Operator

Alright, so let’s start by defining our own class called Ticket.

It’s a simple class with two properties the duration and the creation date.

//simple ticket class
class Ticket {
    //duration
    public int DurationInHours { get; set; }
    //creation time
    public DateTime CreationDate { get; set; }

    //simple constructor
    public Ticket(int durationInHours) {
        //set the duration in hours
        this.DurationInHours = durationInHours;
        //set the creation date to DateTime.Now
        this.CreationDate = DateTime.Now;
    }
}

Now in the main method let’s create two objects and try to add them together.

static void Main(string[] args) {
        //create two tickets
        Ticket firstTicket = new Ticket(2);
        Ticket secondtTicket = new Ticket(3);
        //add the two tickets creating a third ticket object
        Ticket sumTicket = firstTicket + secondtTicket;
     
        //pause
        Console.ReadKey();
    }

This code will throw an error.

As we discussed, there is no way for the compiler to know how to add two tickets together. This is why we need to provide our own logic by overloading the + operator.

So let’s do just that. In our case, we want to add the durations of our tickets, and we want to have a new creation time because it’s a new ticket.

//simple ticket class
class Ticket {
    //duration
    public int DurationInHours { get; set; }
    //creation time
    public DateTime CreationDate { get; set; }

    //simple constructor
    public Ticket(int durationInHours) {
        //set the duration in hours
        this.DurationInHours = durationInHours;
        //set the creation date to DateTime.Now
        this.CreationDate = DateTime.Now;
    }

    //overloading the + operator
    //the class must be public and static followed by the return type and the Operator (+)
    public static Ticket operator +(Ticket a, Ticket b) {
        //return a new ticket object where it's duration = the sum of the durations of ticket a and b
        return new Ticket(a.DurationInHours + b.DurationInHours);
    }
}

Now in the main, since the error is gone let’s just display the result.

static void Main(string[] args) {
      //create two tickets
      Ticket firstTicket = new Ticket(2);
      Ticket secondtTicket = new Ticket(3);
      //add the two tickets creating a third ticket object
      Ticket sumTicket = firstTicket + secondtTicket;
      //display the sum ticket duration in hours
      Console.WriteLine("The total duration in in hours is : " + sumTicket.DurationInHours);
      //pause
      Console.ReadKey();
  }

Alright so as a challenge for you try and overload the other operators -,* and / as well.

 

Lecture Code:

using System;
using System.Collections.Generic;

namespace CSTestingGround {

    class Program {
        static void Main(string[] args) {
            //create two tickets
            Ticket firstTicket = new Ticket(2);
            Ticket secondtTicket = new Ticket(3);
            //add the two tickets creating a third ticket object
            Ticket sumTicket = firstTicket + secondtTicket;
            //display the sum ticket duration in hours
            Console.WriteLine("The total duration in in hours is : " + sumTicket.DurationInHours);
            //pause
            Console.ReadKey();
        }
    }
    //simple ticket class
    class Ticket {
        //duration
        public int DurationInHours { get; set; }
        //creation time
        public DateTime CreationDate { get; set; }

        //simple constructor
        public Ticket(int durationInHours) {
            //set the duration in hours
            this.DurationInHours = durationInHours;
            //set the creation date to DateTime.Now
            this.CreationDate = DateTime.Now;
        }

        //overloading the + operator
        //the class must be public and static followed by the return type and the Operator (+)
        public static Ticket operator +(Ticket a, Ticket b) {
            //return a new ticket object where it's duration = the sum of the durations of ticket a and b
            return new Ticket(a.DurationInHours + b.DurationInHours);
        }
    }
}
Lost in coding? Discover our Learning Paths!
Lost in coding? Discover our Learning Paths!
Tired of being just an average developer?
Stop wasting your time and learn coding the right (and easy) way!
Tired of being just an average developer?
Stop wasting your time and learn coding the right (and easy) way!
Enter your email and we will send you the PDF guide:
Enter your email and we will send you the PDF guide