chapter 13 - operator overloading
DESCRIPTION
kTRANSCRIPT
Operator Overloading 1C# 30
C# 3.0C# 3.0
Chapter 13 – Operator Overloading
© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
Operator O erloading
Operator Overloading 2C# 30
Operator Overloading• Operator overloading is similar to C++:• Operator overloading is similar to C++:
– Use intuitive operator syntax on user-defined types– Methods are defined as operators using the operator keywordO t l d d l h it k– Operators are overloaded only when it makes immediate sense
• C# operator overloading is simpler (andC# operator overloading is simpler (and more limited) than in C++
© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
Operator Overloading ExampleOperator Overloading 3C# 30
Operator Overloading Exampleclass Date { {
...public static bool operator==(Date d1, Date d2) {
t d1 d d2 d && return d1._day == d2._day && ...;}public static bool operator>(Date d1, Date d2) {p p ( , ) {
...}
bli t ti b l t <(D t d1 D t d2) {public static bool operator<(Date d1, Date d2) {return (d2 > d1);
}}public static Date operator+(Date d1, int numDays) {
Date retVal = d1;tV l I tD ( D )retVal.IncrementDays(numDays);
return retVal;}
© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
}}
Operator UsageOperator Overloading 4C# 30
Operator Usageclass DateApp {pp {
static void Main() {Date d1 = new Date (1, 1, 2000);D t d2 d1Date d2 = d1;if (d2 == d1)
Console.WriteLine ("Equal");( q );Date d3 = new Date(1,1,2000);if (d3 != d1)
C l W it Li ("N t E l")Console.WriteLine ("Not Equal");d1++;++d1;;Date d4 = d1 + 5;d4 += 6;
}}}
© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
Operator OverloadingOperator Overloading 5C# 30
Operator Overloading
Operators sho ld be defined as static• Operators should be defined as static class methods– At least one of the parameters must be the type
containing the operatorcontaining the operator
– Cannot modify the syntax, precedence, or associativity of an operatorassociativity of an operator
A i d li i ll• Assignment and equality are automatically implemented for all typesimplemented for all types– Value types and reference types are different, of
course
© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
course…
Which Operators Are AvailableOperator Overloading 6C# 30
Which Operators Are Available
The follo ing nar operators can be• The following unary operators can be overloaded:– +, -, !, ~, ++, --, true, false
The following binary operators can be• The following binary operators can be overloaded: – +, -, *, /, %, &, |, ^, <<, >>
• The comparison operators can be• The comparison operators can be overloaded (in pairs):( )– ==, !=, <, >, <=, >=
© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
What Operators Are AvailableOperator Overloading 7C# 30
What Operators Are Available
• The array indexing operator [] cannot be• The array indexing operator [] cannot be overloaded, but you can define indexers
• Compound assignment operators cannot• Compound assignment operators cannot be overloaded (automatic):– +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=
• The following operators cannot be l d doverloaded:
– =, ., ?:, ->, new, is, sizeof, typeof,
© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
&&, ||
Overriding EqualityOperator Overloading 8C# 30
Overriding Equality
When o erloading eq alit o erride• When overloading equality, override Equals and GetHashCode appropriatelyq pp p y– Ensure that if a.Equals(b) then a.GetHashCode() == b.GetHashCode()()
– Ensure that there’s a good distribution of hash values
Ensure that operator== and Equals are in sync– Ensure that operator== and Equals are in sync
© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
Operator Names in the CLSOperator Overloading 9C# 30
Operator Names in the CLSOperator Sign Operator NameOperator Sign Operator Name
+ (binary) op_Addition
(bi ) S bt t- (binary) op_Subtract
== op_Equality
!= op_Inequality
> op GreaterThan> op_GreaterThan
+= op_AdditionAssignment
I t++ op_Increment
Conversions op_Implicit
op_Explicit
+ (unary) op UnaryPlus
© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
+ (unary) op_UnaryPlus
- (unary) op_UnaryNegation
Operator NotesOperator Overloading 10C# 30
Operator Notes
• Compound arithmetic (e g +=) operators• Compound arithmetic (e.g. +=) operators are automatically generated
• There’s just one increment operator and• There s just one increment operator and one decrement operator– Postfix and prefix semantics are automatically
implemented
• The function call operator is not availablep
© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
User-Defined ConversionsOperator Overloading 11C# 30
User-Defined Conversions
• Users can define conversions between• Users can define conversions between user-defined types and other types– But not two system types
• Conversions are defined as static f tifunctions– One of the parameters must be of the enclosing
type’s type– Declared either explicit or implicit
© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
Conversions ExampleOperator Overloading 12C# 30
Conversions Examplestruct Celsius {{
...public static implicit operator Fahrenheit(Celsius c) {
t ((( t * 9) / 5) 32)return(((c._temp * 9) / 5) + 32);}public static implicit operator Celsius(float temp) {p p p ( p) {
Celsius c;c = new Celsius(temp);
t return c;}public static implicit operator float(Celsius c) {p p p ( ) {
return c._temp;}
}}//Fahrenheit struct definition is very similar
© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
Explicit and Implicit ConversionsOperator Overloading 13C# 30
Explicit and Implicit Conversions
• Declare a conversion explicit if it can• Declare a conversion explicit if it can cause exceptions or lose information ( i i )(precision)– An explicit conversion must be invoked via an
explicit cast operator
• Implicit conversions should not cause any t d ltunexpected results
– No exceptions, no precision loss
© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
Sequence of ConversionsOperator Overloading 14C# 30
Sequence of Conversions
• The compiler will perform a sequence of at• The compiler will perform a sequence of at most two conversions of the form:– Basic conversion followed by user-defined
conversion, -or-– User-defined conversion followed by basic conversion
• For a Celsius object that has a conversion from float this is a valid sequence:from float, this is a valid sequence:
Celsius c = ...;c = 2;//Implicit int to float, implicit float to Celsius
© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
Chapter SummaryOperator Overloading 15C# 30
Chapter Summary
C# operators are• C# operators are– Static methods
– Must have at least one argument of its enclosing type’s typeyp yp
– Can be explicit or implicit
Some operators are automatic• Some operators are automatic
• Beware with redefining equality andBeware with redefining equality and defining new conversions
© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel