Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define New Arithmetic Operation in C#

Tags:

c#

Let's say I've created a simple class.

class Zoo {
  public int lionCount;
  public int cheetahCount;
  Zoo(lions, cheetahs) { 
    lionCount = lions;
    cheetahCount = cheetahs;
  }
}

Now let's say I have 2 zoos.

Zoo zoo1 = new Zoo(1,2);
Zoo zoo2 = new Zoo(3,5);

Is it possible to define arithmetic operation for this class, such that...

Zoo zoo3 = zoo1 + zoo2; //makes a zoo with 4 lions and 7 cheetahs
Zoo zoo4 = zoo1 * zoo2; // makes a zoo with 3 lions and 10 cheetahs

In other words, how can I define custom arithmetic operations for a C# class?

like image 312
Code Whisperer Avatar asked Dec 25 '22 13:12

Code Whisperer


1 Answers

Sure you can using operator overloading

class Zoo 
{
  public int lionCount;
  public int cheetahCount;

  Zoo(int lions, int cheetahs) 
  { 
    lionCount = lions;
    cheetahCount = cheetahs;
  }

  public static Zoo operator +(Zoo z1, Zoo z2) 
  {
    return new Zoo(z1.lionCount + z2.lionCount, z1.cheetahCount + z2.cheetahCount);
  }
}

The other operators are handle pretty much the same way ;-)

For more information about it check https://msdn.microsoft.com/en-us/library/aa288467(v=vs.71).aspx

like image 181
DerApe Avatar answered Jan 10 '23 13:01

DerApe