132
Binary Operators
Unary Operators
Not Overloadable
+ - * / %
(+= -= *= /= %=)
& | ^ << >>
(&= |= ^= <<= >>=)
== != > < >= <=
+ - ! ~ ++ --
true false
&& || = . [ ] ( ) :: ?:
?? -> =>
new as is sizeof
typeof nameof
The comparison operators, as well as true and false, must be
overloaded in pairs. For example, overloading
the equal operator means
that the not equal operator also has to be overloaded.
True and False Operator Overloading
Notice in the previous table that true and false are considered to
be operators. By overloading them, objects
of a class can be used in
conditional statements where the object needs to be evaluated as a
Boolean type. When overloading them, the return types must be bool.
class MyNum
{
public int val;
public MyNum(int i) { val = i; }
public static bool operator true(MyNum a) {
return (a.val != 0);
}
public static bool operator false(MyNum a) {
return (a.val == 0);
}
}
Chapter 22 OperatOr OverlOading
135
© Mikael Olsson 2020
M. Olsson,
C# 8 Quick Syntax Reference,
https://doi.org/10.1007/978-1-4842-5577-3_23
Do'stlaringiz bilan baham: