Guide to the Language


Return Types and Parameters


Download 2 Mb.
Pdf ko'rish
bet56/78
Sana30.04.2023
Hajmi2 Mb.
#1414515
TuriGuide
1   ...   52   53   54   55   56   57   58   59   ...   78
Bog'liq
C sharp

 Return Types and Parameters
When overloading a unary operator, the return type and parameter type 
must be of the enclosing type. On the other hand, when overloading most 
binary operators, the return type can be anything, except for void, and 
only one of the parameters must be of the enclosing type. This means 
that it is possible to further overload a binary operator with other method 
parameters, for example, to allow a MyNum and an int to be added together.
public static MyNum operator +(MyNum a, int b)
{
return new MyNum(a.val + b);
}
 Overloadable Operators
C# allows overloading of almost all operators, as can be seen in the 
following table. The combined assignment operators cannot be 
explicitly overloaded. Instead, they are implicitly overloaded when their 
corresponding arithmetic or bitwise operators are overloaded.
Chapter 22 OperatOr OverlOading


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


133
class MyApp
{
static void Main()
{
MyNum a = new MyNum(10);
if (a) System.Console.Write("true");
else System.Console.Write("false");
}
}
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

Download 2 Mb.

Do'stlaringiz bilan baham:
1   ...   52   53   54   55   56   57   58   59   ...   78




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling