[C#] C# Operator Overloading & Lists

Date:     Updated:

Categories:

Tags:

📋 This is my note-taking from what I learned in the class “Programming 2”


Operator overloading

Operator overloading in C# allows you to define custom implementations for operators, such as +, -, *, /, ==, !=, and more, for your own custom types. It enables you to use operators with your objects in a way that makes sense based on the context and behavior of your types.

To overload an operator, you need to define a special method within your class that corresponds to the operator you want to overload. These methods are called operator overloading methods. They are defined using the operator keyword followed by the operator you want to overload.

//Operator Overloading
using System;

namespace OperatorOverloadingDemo
{
  class Program
  {
    static void Main(string[] args)
    {
      Complex c1 = new Complex(3, 7);
      c1.Display();
      Complex c2 = new Complex(5, 2);
      c2.Display();
      Complex c3 = c1 + c2;
      c3.Display();
      Console.ReadKey();
    }
  }

  public class Complex
  {
    private int real;
    private int img;
    public Complex(int r = 0, int i = 0)
    {
      real = r;
      img = i;
    }
    public static Complex operator +(Complex c1, Complex c2)
    {
      Complex temp = new Complex();
      temp.real = c1.real + c2.real;
      temp.img = c1.img + c2.img;
      return temp;
    }
    public void Display()
    {
      Console.WriteLine($"{real} + i{img}");
    }
  }
}
using System;
namespace OperatorOverloadingDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Distance d1 = new Distance(3, 9);
            Console.WriteLine("d1 details: ");
            d1.Display();
            Distance d2 = new Distance(5, 7);
            Console.WriteLine("d2 details: ");
            d2.Display();
            Distance d3 = d1 + d2;
            Console.WriteLine("d3 details: ");
            d3.Display();
            Console.ReadKey();
        }
    }
    public class Distance
    {
        private int feet;
        private int inch;
        public Distance(int f = 0, int i = 0)
        {
            feet = f;
            inch = i;
        }
        public static Distance operator +(Distance c1, Distance c2)
        {
            Distance temp = new Distance();
            temp.feet = c1.feet + c2.feet;
            temp.inch = c1.inch + c2.inch;
            if (temp.inch >= 12)
            {
                ++temp.feet;
                temp.inch -= 12;
            }
            return temp;
        }
        public void Display()
        {
            Console.WriteLine($"{feet} feets and {inch} inches");
        }
    }
}

The below function implements the addition operator (+) for a user-defined class Box. It adds the attributes of two Box objects and returns the resultant Box object.

public static Box operator+ (Box b, Box c) {
   Box box = new Box();
   box.length = b.length + c.length;
   box.breadth = b.breadth + c.breadth;
   box.height = b.height + c.height;
   return box;
}


Implementing the Operator Overloading

The following program shows the complete implementation:

using System;

namespace OperatorOvlApplication {
   class Box {
      private double length;   // Length of a box
      private double breadth;  // Breadth of a box
      private double height;   // Height of a box

      public double getVolume() {
         return length * breadth * height;
      }
      public void setLength( double len ) {
         length = len;
      }
      public void setBreadth( double bre ) {
         breadth = bre;
      }
      public void setHeight( double hei ) {
         height = hei;
      }

      // Overload + operator to add two Box objects.
      public static Box operator+ (Box b, Box c) {
         Box box = new Box();
         box.length = b.length + c.length;
         box.breadth = b.breadth + c.breadth;
         box.height = b.height + c.height;
         return box;
      }
   }
   class Tester {
      static void Main(string[] args) {
         Box Box1 = new Box();   // Declare Box1 of type Box
         Box Box2 = new Box();   // Declare Box2 of type Box
         Box Box3 = new Box();   // Declare Box3 of type Box
         double volume = 0.0;    // Store the volume of a box here

         // box 1 specification
         Box1.setLength(6.0);
         Box1.setBreadth(7.0);
         Box1.setHeight(5.0);

         // box 2 specification
         Box2.setLength(12.0);
         Box2.setBreadth(13.0);
         Box2.setHeight(10.0);

         // volume of box 1
         volume = Box1.getVolume();
         Console.WriteLine("Volume of Box1 : {0}", volume);

         // volume of box 2
         volume = Box2.getVolume();
         Console.WriteLine("Volume of Box2 : {0}", volume);

         // Add two object as follows:
         Box3 = Box1 + Box2;

         // volume of box 3
         volume = Box3.getVolume();
         Console.WriteLine("Volume of Box3 : {0}", volume);
         Console.ReadKey();
      }
   }
}

//Output:
//Volume of Box1 : 210
//Volume of Box2 : 1560
//Volume of Box3 : 5400


Overloadable and Non-Overloadable Operators

The following table describes the overload ability of the operators in C#:

Sr.No. Operators & Description
1 +, -, !, ~, ++, –
  These unary operators take one operand and can be overloaded.
2 +, -, *, /, %
  These binary operators take one operand and can be overloaded.
3 ==, !=, <, >, <=, >=
  The comparison operators can be overloaded.
4 &&, ||
  The conditional logical operators cannot be overloaded directly.
5 +=, -=, *=, /=, %=
  The assignment operators cannot be overloaded.
6 =, ., ?:, ->, new, is, sizeof, typeof
  These operators cannot be overloaded.

Example:

using System;

namespace OperatorOvlApplication {
   class Box {
      private double length;    // Length of a box
      private double breadth;   // Breadth of a box
      private double height;    // Height of a box

      public double getVolume() {
         return length * breadth * height;
      }
      public void setLength( double len ) {
         length = len;
      }
      public void setBreadth( double bre ) {
         breadth = bre;
      }
      public void setHeight( double hei ) {
         height = hei;
      }

      // Overload + operator to add two Box objects.
      public static Box operator+ (Box b, Box c) {
         Box box = new Box();
         box.length = b.length + c.length;
         box.breadth = b.breadth + c.breadth;
         box.height = b.height + c.height;
         return box;
      }
      public static bool operator == (Box lhs, Box rhs) {
         bool status = false;
         if (lhs.length == rhs.length && lhs.height == rhs.height
            && lhs.breadth == rhs.breadth) {

            status = true;
         }
         return status;
      }
      public static bool operator !=(Box lhs, Box rhs) {
         bool status = false;

         if (lhs.length != rhs.length || lhs.height != rhs.height ||
            lhs.breadth != rhs.breadth) {

            status = true;
         }
         return status;
      }
      public static bool operator <(Box lhs, Box rhs) {
         bool status = false;

         if (lhs.length < rhs.length && lhs.height < rhs.height
            && lhs.breadth < rhs.breadth) {

            status = true;
         }
         return status;
      }
      public static bool operator >(Box lhs, Box rhs) {
         bool status = false;

         if (lhs.length > rhs.length && lhs.height >
            rhs.height && lhs.breadth > rhs.breadth) {

            status = true;
         }
         return status;
      }
      public static bool operator <=(Box lhs, Box rhs) {
         bool status = false;

         if (lhs.length <= rhs.length && lhs.height
            <= rhs.height && lhs.breadth <= rhs.breadth) {

            status = true;
         }
         return status;
      }
      public static bool operator >=(Box lhs, Box rhs) {
         bool status = false;

         if (lhs.length >= rhs.length && lhs.height
            >= rhs.height && lhs.breadth >= rhs.breadth) {

            status = true;
         }
         return status;
      }
      public override string ToString() {
         return String.Format("({0}, {1}, {2})", length, breadth, height);
      }
   }
   class Tester {
      static void Main(string[] args) {
         Box Box1 = new Box();   // Declare Box1 of type Box
         Box Box2 = new Box();   // Declare Box2 of type Box
         Box Box3 = new Box();   // Declare Box3 of type Box
         Box Box4 = new Box();
         double volume = 0.0;    // Store the volume of a box here

         // box 1 specification
         Box1.setLength(6.0);
         Box1.setBreadth(7.0);
         Box1.setHeight(5.0);

         // box 2 specification
         Box2.setLength(12.0);
         Box2.setBreadth(13.0);
         Box2.setHeight(10.0);

         //displaying the Boxes using the overloaded ToString():
         Console.WriteLine("Box 1: {0}", Box1.ToString());
         Console.WriteLine("Box 2: {0}", Box2.ToString());

         // volume of box 1
         volume = Box1.getVolume();
         Console.WriteLine("Volume of Box1 : {0}", volume);

         // volume of box 2
         volume = Box2.getVolume();
         Console.WriteLine("Volume of Box2 : {0}", volume);

         // Add two object as follows:
         Box3 = Box1 + Box2;
         Console.WriteLine("Box 3: {0}", Box3.ToString());

         // volume of box 3
         volume = Box3.getVolume();
         Console.WriteLine("Volume of Box3 : {0}", volume);

         //comparing the boxes
         if (Box1 > Box2)
            Console.WriteLine("Box1 is greater than Box2");
         else
            Console.WriteLine("Box1 is not greater than Box2");

         if (Box1 < Box2)
            Console.WriteLine("Box1 is less than Box2");
         else
            Console.WriteLine("Box1 is not less than Box2");

         if (Box1 >= Box2)
            Console.WriteLine("Box1 is greater or equal to Box2");
         else
            Console.WriteLine("Box1 is not greater or equal to Box2");

         if (Box1 <= Box2)
            Console.WriteLine("Box1 is less or equal to Box2");
         else
            Console.WriteLine("Box1 is not less or equal to Box2");

         if (Box1 != Box2)
            Console.WriteLine("Box1 is not equal to Box2");
         else
            Console.WriteLine("Box1 is not greater or equal to Box2");
         Box4 = Box3;

         if (Box3 == Box4)
            Console.WriteLine("Box3 is equal to Box4");
         else
            Console.WriteLine("Box3 is not equal to Box4");

         Console.ReadKey();
      }
   }
}

/* Output
Box 1: (6, 7, 5)
Box 2: (12, 13, 10)
Volume of Box1 : 210
Volume of Box2 : 1560
Box 3: (18, 20, 15)
Volume of Box3 : 5400
Box1 is not greater than Box2
Box1 is less than Box2
Box1 is not greater or equal to Box2
Box1 is less or equal to Box2
Box1 is not equal to Box2
Box3 is equal to Box4 */


Lists

Why do we use list?

There are several reasons why we might choose to use lists instead of arrays in C#:

  1. Dynamic Size:
    Lists in C# have a dynamic size, meaning we can add or remove elements from the list at runtime. This provides flexibility when working with collections of items that may grow or shrink over time. Arrays, on the other hand, have a fixed size once they are created.
  2. Easy Modification:
    Lists provide convenient methods for adding, removing, and modifying elements. We can use methods like Add(), Remove(), Insert(), and Clear() to manipulate the contents of a list. Arrays require manual resizing or creating a new array to accommodate changes in size.
  3. Flexibility:
    Lists offer a more flexible and convenient API compared to arrays. They provide a variety of useful methods and properties, such as sorting, searching, filtering, and iterating through elements. These built-in functionalities simplify common operations on collections of data.
  4. Type Safety:
    Lists in C# are type-safe, which means they can only store elements of a specific type. This helps prevent type-related errors during compilation and provides better code reliability. Arrays, on the other hand, can store elements of different types in the same array, which can lead to potential type-related issues.
  5. Integration with LINQ:
    Lists seamlessly integrate with LINQ (Language-Integrated Query), which provides powerful querying and manipulation capabilities for collections. LINQ allows us to perform operations like filtering, sorting, projecting, and aggregating data with a concise and expressive syntax.

Overall, lists in C# offer more flexibility, convenience, and functionality compared to arrays, making them a preferred choice in many scenarios where dynamic collections of data are involved.

Arrays → int a[2] → a[0], a[1], a[2] (we can assign total 3 values)

List<string> subjects = new List<string>(){"English", "Math"};

List<int> num = new List<int>(){1,2,3};

//Access value
subjects[0]; //"English"
num[0]; //1

//Add elements -> Add values after the list
num.Add(4); //{1,2,3,4}
//-> This is not available in Arrays unlike Lists

//Insert elements -> We need to set the place where we want to insert value
num.Insert(4, 5) //{1,2,3,4,5}
//-> (fir, sec) -> fir is location and sec is value

//Remove elements -> We need to set the place where we want to remove value
num.Remove(4) //{1,2,3,5} -> It will remove 4 from the list
//-> remove specific value(4)
num.RemoveAt(4) //{1,2,3,4} -> It will remove 5 from the list
//-> remove specific index value(5=>value of index 4)

//Count elements
num.Count(); //4 (how many number of elements within the list)

//Clear elements from the list
num.Clear();
num.Count(); //

num.Contains(2); //Result is "True"
//Array "African" = ["Cairo", "Johan..."]
//Array Asian = ["Seoul", "Japan"]
List<string> city = new List<string>();

//AddRange() -> Add two cities to the list "city"
city.AddRange(african); //List: Cairo Johan...

//InsertRange()
city.InsertRange(0, asian); //List: Seoul Japan Cairo Johan...

//RemoveRange()
city.RemoveRange(1, 2); //List: Seoul Johan...
//-> cuz I removed index 1 to index 2




Back to Top

See other articles in Category CS

Leave a comment