Understanding Operator Overloading in C#
 
Published: 02 Apr 2007
Abstract
In this article Joydip discusses the concept of Operator Overloading in C# with the help of code samples.
by Joydip Kanjilal
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 39881/ 100

Introduction

Operator overloading (a feature that was initially introduced in C++) is a concept that enables us to redefine the existing operators so that they can be used on user defined types like classes and structs. This article discusses Operator Overloading in C# with a lot of code samples.

Introducing Operator Overloading

Whenever you overload an operator in C#, you have specific operator methods created that are related to the operator that you overload. Hence, when you overload the + operator, the overloaded operator method name is operator+. Note that all the overloaded operator methods are named "operator."  Further, all operator methods in C# are static. To know more on static and non-static methods, refer to my post at my blog at the link given below.

Static vs Non - Static Methods

Note that operator overloading is a feature of the C# language, not of the IL. Visual Basic .NET does not support operator overloading. Hence, if you were to access C# methods from non C# languages, ensure that you provide some methods that act as a wrapper on your operator methods to facilitate compliancy. If you have overloaded the + operator in your C# class, ensure that you have a method (something like Add or AddValues) that would acts as a wrapper around your operator+ method so as to enable the same to be accessed from outside.

I would not like to drill down into what are the operators that can be overloaded in C# and those that cannot be overloaded or the associated rules. There is plenty of stuff on it. You can find some of them at the following links.

Operator Overloading In C#

Overloading Operators

Implementing Operator Overloading in C#

This section discusses how we can implement operator overloading in C#. Imagine you have a class called Fps that encapsulates some of the foot pound second operations, i.e., you can add two instances of type Fps, compare whether one is greater than the other, increment or decrement an instance, etc.

The following is the source code for the Fps class.

Listing 1

class Fps
{
  private int feet, inch;
 
  public Fps()
  {
  
  }
 
  public Fps(int f, int i)
  {
      feet = f;
      inch = i;
  }
//Some code
}

Suppose you want to add two Fps class instances and create a new instance out of it. Now, with Fps being a class, you cannot use this sort of operation on instances of this class unless you overload the + operator. The overloaded operator method in this case would be named operator+. This being a binary operator, you would be required to pass two parameters to this method to operate. The following code snippet illustrates how the binary operators +,-,> or < can be overloaded.

Listing 2

public static Fps operator + (Fps obj1, Fps obj2)
{
  Fps temp = new Fps();
  temp.feet = obj1.feet + obj2.feet;
  temp.inch = obj1.inch + obj2.inch;
 
  if (temp.inch > 12)
  {
    temp.feet++;
    temp.inch -= 12;
  }
 
  return temp;
}
 
public static Fps operator - (Fps obj1, Fps obj2)
{
  int value1 = obj1.feet * 12+obj1.inch;
  int value2 = obj2.feet * 12+obj2.inch;
  int value3 = value1 - value2;
  return new Fps(value3 / 12, value3 % 12);
  ;
}
 
public static bool operator > (Fps obj1, Fps obj2)
{
  int value1 = obj1.feet * 12+obj1.inch;
  int value2 = obj2.feet * 12+obj2.inch;
 
  if (value1 > value2)
    return true;
  return false;
}
 
public static bool operator < (Fps obj1, Fps obj2)
{
  int value1 = obj1.feet * 12+obj1.inch;
  int value2 = obj2.feet * 12+obj2.inch;
 
  if (value1 < value2)
    return true;
  return false;
}
            

Similarly, you could use the unary ++ or the -- operator to increment or decrement an instance of this class by one. These being unary operators, you require only one argument to the operator++ or the operator-- overloaded methods. The following code snippet shows how the unary operators ++ and -- can be overloaded.

Listing 3

public static Fps operator++(Fps obj)
{
  obj.inch++;
 
  if (obj.inch > 12)
  {
    obj.feet++;
    obj.inch -= 12;
  }
 
  return obj;
}
 
public static Fps operator--(Fps obj)
{
  obj.inch--;
 
  if (obj.inch < 0)
  {
    obj.feet--;
    obj.inch += 12;
  }
 
  return obj;
}

You can also use the implicit operator to convert an integer value to an Fps instance. You can know more on using the implicit operator in C# at the following link.

Understanding implicit operator overloading in C#

The following code snippet illustrates how the implicit operator can be used.

Listing 4

public static implicit operator Fps(int x)
{
  Fps f = new Fps();
  f.feet = x / 12;
  f.inch = x % 12;
  return f;
}

The following is the complete source code for the Fps class.

Listing 5

using System;
 
namespace OperatorOverloading
{
  class Fps
  {
    private int feet, inch;
 
    public Fps(){
 
    }
 
    public Fps(int f, int i)
    {
      feet = f;
      inch = i;
    }
 
    //Unary Operators
    public static Fps operator++(Fps obj)
    {
      obj.inch++;
 
      if (obj.inch > 12)
      {
        obj.feet++;
        obj.inch -= 12;
      }
 
      return obj;
    }
 
    public static Fps operator--(Fps obj)
    {
      obj.inch--;
 
      if (obj.inch < 0)
      {
        obj.feet--;
        obj.inch += 12;
      }
 
      return obj;
    }
 
    //Binary Operators
    public static Fps operator + (Fps obj1, Fps obj2)
    {
      Fps temp = new Fps();
      temp.feet = obj1.feet + obj2.feet;
      temp.inch = obj1.inch + obj2.inch;
 
      if (temp.inch > 12)
      {
        temp.feet++;
        temp.inch -= 12;
      }
 
      return temp;
    }
 
    public static Fps operator - (Fps obj1, Fps obj2)
    {
      int value1 = obj1.feet * 12+obj1.inch;
      int value2 = obj2.feet * 12+obj2.inch;
      int value3 = value1 - value2;
      return new Fps(value3 / 12, value3 % 12);
      ;
    }
 
    public static bool operator > (Fps obj1, Fps obj2)
    {
      int value1 = obj1.feet * 12+obj1.inch;
      int value2 = obj2.feet * 12+obj2.inch;
 
      if (value1 > value2)
        return true;
      return false;
    }
 
    public static bool operator < (Fps obj1, Fps obj2)
    {
      int value1 = obj1.feet * 12+obj1.inch;
      int value2 = obj2.feet * 12+obj2.inch;
 
      if (value1 < value2)
        return true;
      return false;
    }
 
    //Implicit conversion operator
    public static implicit operator Fps(int x)
    {
      Fps f = new Fps();
      f.feet = x / 12;
      f.inch = x % 12;
      return f;
    }
 
    public override string ToString()
    {
      return ("Feet = " + this.feet + "  Inch = " + this.inch);
    }
  }
}

Let us now use this class to perform the various operations that we discussed about. Refer to the code snippet below:

Listing 6

Fps f1 = new Fps(5,2); //Create new Fps instance
Console.WriteLine(f1.ToString());
Fps f2 = new Fps(2,11); //Create another Fps instance
Console.WriteLine(f2.ToString());
Fps f3 = f1 + f2; //Binary operation
Console.WriteLine(f3.ToString());
f3++; //Unary operation
Console.WriteLine(f3.ToString());
Fps f4 = 100; //Perform an explicit cast from integer to an Fps instance
Console.WriteLine(f4.ToString());
References

Conclusion

This article has discussed what Operator Overloading is and how we can implement the same in C#.



User Comments

No comments posted yet.






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2019 ASPAlliance.com  |  Page Processed at 2019-08-19 8:49:42 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search