Overriding the + and – operators in C# .NET
December 18, 2015 Leave a comment
It’s easy to override the mathemtical operators like + or – in C# to build custom operations.
Consider the following simple Rectangle class:
public class Rectangle { public Rectangle(int width, int height) { Height = height; Width = width; } public int Width { get; set; } public int Height { get; set; } }
…and the following two Rectangle objects:
Rectangle start = new Rectangle(8, 10); Rectangle additional = new Rectangle(4, 3);
Let’s say that you’d like to add the width and height of “additional” to “start” so that “start” will grow according to the dimensions of “additional”. There are several ways to achieve this in code one of them is to override the mathematical operators ‘+’ and ‘-‘. It’s very easy, you just need to be aware of the “operator” keyword. The Rectangle class can be extended as follows:
public static Rectangle operator +(Rectangle startingRectangle, Rectangle anotherRectangle) { startingRectangle.Height += anotherRectangle.Height; startingRectangle.Width += anotherRectangle.Width; return startingRectangle; } public static Rectangle operator -(Rectangle startingRectangle, Rectangle anotherRectangle) { startingRectangle.Height -= anotherRectangle.Height; startingRectangle.Width -= anotherRectangle.Width; if (startingRectangle.Height < 0) startingRectangle.Height = 0; if (startingRectangle.Width < 0) startingRectangle.Width = 0; return startingRectangle; }
…and then you can add the two rectangles:
start += additional;
“start” will now have a height of 13 and width of 12. Similarly “start” can shrink as follows:
start -= additional;
“start” will now have a height of 7 and width of 4.
View all various C# language feature related posts here.