Operator Overloading in C#
Operator overloading allows developers to redefine the behavior of operators (like +, -, *, ==) for custom classes and structs. It makes objects behave like built-in types when using operators.
Key Points:
- Uses the
operatorkeyword. - Must be defined inside a class or struct.
- At least one parameter must be a user-defined type.
C# Example:
class CarSpeed
{
public int Speed { get; set; }
public CarSpeed(int speed)
{
Speed = speed;
}
public static CarSpeed operator +(CarSpeed c1, CarSpeed c2)
{
return new CarSpeed(c1.Speed + c2.Speed);
}
}
class Program
{
static void Main()
{
CarSpeed car1 = new CarSpeed(60);
CarSpeed car2 = new CarSpeed(40);
CarSpeed total = car1 + car2;
Console.WriteLine("Total Speed: " + total.Speed);
}
}
Output:
Total Speed: 100
No comments:
Post a Comment