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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With