What is Operator Overloading?
Operator overloading is a feature in C# that allows you to define custom behaviors for standard operators such as '+', '-', '*', '/', '==', '!=', etc., for user-defined types (classes or structs). This enables you to work with instances of your custom types using the same syntax as built-in types.
Here's an example of operator overloading in C#:
using System;
public class Complex {
public double Real { get; set; }
public double Imaginary { get; set; }
public Complex(double real, double imaginary) {
Real = real;
Imaginary = imaginary;
}
public static Complex operator +(Complex c1, Complex c2) {
return new Complex(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary);
}
public override string ToString() {
return $"{Real} + {Imaginary}i";
}
}
class Program {
static void Main(string[] args) {
Complex complex1 = new Complex(3, 4);
Complex complex2 = new Complex(1, 2);
Complex sum = complex1 + complex2;
Console.WriteLine($"Sum: {sum}");
}
}
In this example:
-
We define a 'Complex' class to represent complex numbers with real and imaginary parts.
- We overload the '+' operator using the operator keyword, which allows us to add two 'Complex' objects together by defining custom behavior for the '+' operator.
- Inside the '+' operator overload, we perform the addition of the real and imaginary parts separately and create a new 'Complex' object with the result.
- We override the ToString method to provide a meaningful string representation of the 'Complex' object.
In the 'Main' method:
-
We create two 'Complex' instances: 'complex1' and 'complex2'.
- We use the overloaded '+' operator to add these two complex numbers together, and the result is stored in the sum variable.
- Finally, we print the sum using the custom 'ToString' method.
Operator overloading allows you to define intuitive and expressive operations for your custom types, making your code more readable and natural when working with instances of those types.