#396 – Operators as Class Members
August 24, 2011 Leave a comment
In C#, an operator is a symbol that defines some operation that should take place when evaluating an expression.
For example, the plus sign (+) is an operator that is typically used to add two numbers, or two instances of a class.
int a = 5 + 6; // 11 string s = "Corn" + "dog"; // Corndog
For most operators, if you try using them on instances of a class that you define, the operator will have no meaning and you’ll get a compile-time error. (With the exception of the equality (==) and inequality (!=) operators, which are automatically defined for every type).
If you want a particular operator to make sense for instances of a class that you define, you can define that operator as a member of your class. For example, I could define the plus (+) operator for the Dog class, such that it merges the dog’s names and adds their ages.