codescracker


c#

C# Operator Overloading



« Previous Tutorial Next Tutorial »


You are free to redefine or overload most of the built-in operators available in C#. Basically, overloaded operators are the functions with special names, the keyword operator followed by the symbol for the operator being defined. Here is an example showing operator overloading in C#:

public static Box operator+ (Box b, Box c)
{
   Box box = new Box();
   box.leng = b.leng + c.leng;
   box.brea = b.brea + c.brea;
   box.heig = b.heig + c.heig;
   return box;
}

C# Operator Overloading Example

Here is an example program, demonstrates the concept of operator overloading in C#:

using System;
namespace OperatorOverloadingExample
{
	class CubeClass
	{
		private double leng;
		private double brea;
		private double heig;
	
		public double calculateVolume()
		{
			return leng * brea * heig;
		}	
		
		public void initializeLength(double len)
		{
			leng = len;
		}
	
		public void initializeBreadth(double bre)
		{
			brea = bre;
		}	
	
		public void initializeHeight(double hei)
		{
			heig = hei;
		}	
		
		// Overload + operator to add two CubeClass objects.
		public static CubeClass operator+ (CubeClass b, CubeClass c)
		{
			CubeClass box = new CubeClass();
			box.leng = b.leng + c.leng;
			box.brea = b.brea + c.brea;
			box.heig = b.heig + c.heig;
			return box;
		}
	}
	class Tester
	{
		static void Main(string[] args)
		{
			CubeClass Box1 = new CubeClass();   // Declared Box1 of type CubeClass
			CubeClass Box2 = new CubeClass();   // Declared Box2 of type CubeClass
			CubeClass Box3 = new CubeClass();   // Declared Box3 of type CubeClass
			double vol = 0.0;
	
			Box1.initializeLength(6.0);
			Box1.initializeBreadth(7.0);
			Box1.initializeHeight(5.0);
	
			Box2.initializeLength(12.0);
			Box2.initializeBreadth(13.0);
			Box2.initializeHeight(10.0);
	
			vol = Box1.calculateVolume();
			Console.WriteLine("Box1 Volume = {0}", vol);
	
			vol = Box2.calculateVolume();
			Console.WriteLine("Box2 Volume = {0}", vol);
	
			Box3 = Box1 + Box2;	
	
			vol = Box3.calculateVolume();
			Console.WriteLine("Box3 Volume = {0}", vol);
			Console.ReadKey();
		}	
	}	
}

Now when we compile and run the above program then we will get the following output:

Box1 Volume = 210
Box2 Volume = 1560
Box3 Volume = 5400

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test