Overriding the + and – operators in C# .NET

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.

Unknown's avatarAbout Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

One Response to Overriding the + and – operators in C# .NET

  1. Brian Webb's avatar Brian Dead Rift Webb says:

    Reblogged this on Brian By Experience.

Leave a comment

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

ARCHIVED: Bite-size insight on Cyber Security for the not too technical.