Introduction to Operator Overloading in C#

C# Programming Guide
Operator overloading is a form of polymorphism in which operators can be redefined to perform different operations depending upon the types of their arguments. It is mainly used to perform operations on user-defined data types. For example, a programmer can use the same “+” operator to add two integers or combine two strings by just overloading it. However, you can use operator overloading to perform operations on fundamental data types as well.

There are several types of operators, including relational, logical, and mathematical. In this C# programming tutorial, we will take a look at how developers can overload operators (i.e., add extra meaning to existing operators) in C#.

Read: Working with Math Operators in C#

What is Operator Overloading?

Operator overloading (originally a C++ feature) is a notion that allows programmers to redefine existing operators so that they may be used on user-defined types, such as classes and structs. Also known as ad hoc polymorphism, operator overloading allows C# coders to interact with user-defined types in the same manner that they can with basic data types. It is an example of compile-time polymorphism in which the compiler is able to know which operator to overload and which method to invoke at compile time.

Operator overloading is the ability to make an operator perform different operations on operands of different data types. It is a feature of object-oriented programming (OOP) languages that allows you to change the way an operator works on a per-type basis. To overload an operator in C#, you must define a static function that uses the same name of an operator.

Depending on their function and the number of operands on which they operate, operators can be unary, binary, comparison, assignment, and so forth. Although most of the operators can be overloaded, there are certain caveats. To put it simply, not all operators can be overloaded. For example, you cannot overload the following operators in C#:

=, ., ?:, ->, new, is, sizeof, typeof
+=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=

Read: Working with Loops in C#

Benefits of Operator Overloading

The support for operator overloading is a built-in feature in most programming languages. Developers need operators to write expressions; operator overloading allows you to change the behavior of an operator in order to work on objects of your own classes. This is the process of changing the way in which an operator works for user-defined types. So you can use operators with user-defined types in expressions much the same way you do with fundamental data types.

This feature makes C# one of the most flexible object-oriented programming languages and helps in performing different operations on a class object using operators. To sum up, operator overloading adds flexibility and improves the readability of your code.

How to Overload an Operator in C#

Operator overloading – or ad-hoc polymorphism as it is called – allows you to deal with user-defined types in the same manner that you would work with basic data types. Operator Overloading enables us to use the same operator sign (+) with different types of values (numbers and strings). Operators are not only used with numbers, but also with object references, and that includes objects of classes we create. When we define our own classes, we can decide how operators work with instances of those classes.

To overload an operator, you need to follow these rules:

  • One of the operands in an operator function must be of the containing class.
  • An operator function must be a static function.
  • An operator function can return any type except void.

Implementing Operator Overloading in C#

Operators are overloaded by means of operator functions, or methods, which are regular functions with special names. The keyword operator in your source code followed by the symbol of the operator being overloaded lets the compiler know that the function is an operator function. For example, the plus (+) symbol can be used to add two integers, as well as, concatenate two strings. In C++, an operator can be overloaded by specifying more than one definition for it.

Now, consider the following C# code example demonstrating operator overloading:

class FeetToInch
{
    private int feet, inch;
    public FeetToInch()
    {
    }
    public FeetToInch(int f, int i)
    {
        feet = f;
        inch = i;
    }
}

The FeetToInch class above contains two variables – feet and inch. In this class, we will add methods to demonstrate how operator overloading can be implemented in C#.

Read: C# Tools for Code Quality

Overloading Unary Operators in C#

The code snippet given below illustrates how you can overload unary operators in C#:

    public static FeetToInch operator ++(FeetToInch  feetToInch)
    {
        feetToInch.inch++;
        if (feetToInch.inch > 12)
        {
            feetToInch.feet++;
            feetToInch.inch -= 12;
        }
        return feetToInch;
    }

    public static FeetToInch operator --(FeetToInch feetToInch)
    {
        feetToInch.inch--;
        if (feetToInch.inch < 0)
        {
            feetToInch.feet--;
            feetToInch.inch += 12;
        }
        return feetToInch;
    }

Overloading Binary Operators in C#

The following code snippet illustrates how you can overload binary operators in C#:

public static FeetToInch operator +(FeetToInch feetToInch1, FeetToInch feetToInch2)
    {
        FeetToInch temp = new FeetToInch();
        temp.feet = feetToInch1.feet + feetToInch2.feet;
        temp.inch = feetToInch1.inch + feetToInch2.inch;
        if (temp.inch > 12)
        {
            temp.feet++;
            temp.inch -= 12;
        }
        return temp;
    }
public static FeetToInch operator -(FeetToInch feetToInch1, FeetToInch feetToInch2)
    {
        int x = feetToInch1.feet * 12 + feetToInch1.inch;
        int y = feetToInch2.feet * 12 + feetToInch2.inch;
        int z = x - y;
        return new FeetToInch(z / 12, z % 12);
    }

Here’s the complete code example for your reference:

class FeetToInch
{
    private int feet, inch;
    public FeetToInch()
    {
    }
    public FeetToInch(int f, int i)
    {
        feet = f;
        inch = i;
    }
    public static FeetToInch operator ++(FeetToInch  feetToInch)
    {
        feetToInch.inch++;
        if (feetToInch.inch > 12)
        {
            feetToInch.feet++;
            feetToInch.inch -= 12;
        }
        return feetToInch;
    }
    public static FeetToInch operator --(FeetToInch feetToInch)
    {
        feetToInch.inch--;
        if (feetToInch.inch < 0) { feetToInch.feet--; feetToInch.inch += 12; } return feetToInch; } public static FeetToInch operator +(FeetToInch feetToInch1, FeetToInch feetToInch2) { FeetToInch temp = new FeetToInch(); temp.feet = feetToInch1.feet + feetToInch2.feet; temp.inch = feetToInch1.inch + feetToInch2.inch; if (temp.inch > 12)
        {
            temp.feet++;
            temp.inch -= 12;
        }
        return temp;
    }
    public static FeetToInch operator -(FeetToInch feetToInch1, FeetToInch feetToInch2)
    {
        int x = feetToInch1.feet * 12 + feetToInch1.inch;
        int y = feetToInch2.feet * 12 + feetToInch2.inch;
        int z = x - y;
        return new FeetToInch(z / 12, z % 12);
    }
    public override string ToString()
    {
        return ("Feet: " + this.feet + "  Inch: " + this.inch);
    }
}

Finally, you can test the FeetToInch class using the following piece of C# code:

FeetToInch obj = new FeetToInch(9, 5);
Console.WriteLine(obj.ToString());

Read: Productivity Tools for .NET Developers

Final Thoughts on C# Operator Overloading

Operators are one of the most common features of any programming language. You can take advantage of operators to perform mathematical, logical, and other operations on data in your classes and structs. Operator overloading helps improve the readability and usability of your code. You cannot overload assignment operators, but if you have overloaded a binary operator, such as the + operator, the += operator can also be overloaded.

Read more C# programming and software development tutorials.

Joydip Kanjilal
Joydip Kanjilal
A Microsoft Most Valuable Professional in ASP.NET, Speaker, and Author of several books and articles. More than 25 years of experience in IT with more than 18 years in Microsoft .NET and its related technologies. He was selected as a Community Credit Winner at http://www.community-credit.com several times. He has authored 8 books and more than 500 articles in some of the most reputed sites worldwide including MSDN, Info World, CodeMag, Tech Beacon, Tech Target, Developer, CodeGuru, and more.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read