You are on page 1of 8

C# 30

Operator Overloading 1

C# 3.0
Chapter 13 – Operator Overloading

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

C# 30

Operator Overloading 2

Operator Overloading
O erloading
• Operator overloading is similar to C++:
– Use intuitive operator syntax on user-defined types
– Methods are defined as operators using the
operator keyword
– Operators
O
t
are overloaded
l d d only
l when
h it makes
k
immediate sense

• C# 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

return retVal.. 14-18 Baruch Hirsch St. ++d1. D t  d2   d1 Date d2 = d1. .. ) { public static bool operator>(Date d1. int numDays) { Date retVal = d1. l") d1++.. 14-18 Baruch Hirsch St. Date d3 = new Date(1. if (d2 == d1) ( q ). } } © Copyright SELA Software & Education Labs Ltd. Date d2) { t <(D t  d1  D t  d2) { return (d2 > d1). Date d2) { . Console.WriteLine l W it Li ("N t E ("Not Equal").. t  d1 d    d2 d  &&  } p p ( .1. Date d4 = d1 + 5. Date d2) { return d1.2000). d4 += 6._day && .IncrementDays(numDays).. Bnei Brak 51202 Israel . } } © Copyright SELA Software & Education Labs Ltd.. tV l I tD ( D ) retVal.C# 30 Operator Overloading 3 Operator Overloading Example class Date {   { . 1. } public static Date operator+(Date d1.WriteLine ("Equal"). } public static bool bli   t ti  b l operator<(Date d1. Bnei Brak 51202 Israel C# 30 Operator Overloading 4 Operator Usage class DateApp pp { static void Main() { Date d1 = new Date (1. 2000). public static bool operator==(Date d1. if (d3 != d1) C Console.._day == d2.

C# 30 Operator Overloading 5 Operator Overloading • Operators should sho ld be defined as static class methods – At least one of the parameters must be the type containing the operator – Cannot modify the syntax. &. ~. /. >> • The comparison operators can be ) overloaded ((in pairs): – ==. 14-18 Baruch Hirsch St. --. !=. -. of course course… © Copyright SELA Software & Education Labs Ltd. or associativity of an operator • A Assignment i and d equality li are automatically i ll implemented for all types – Value types and reference types are different. %. -. Bnei Brak 51202 Israel . Bnei Brak 51202 Israel C# 30 Operator Overloading 6 Which Operators Are Available • The follo following ing unary nar operators can be overloaded: – +. <=. precedence. ^. *. <. true. false • The following binary operators can be overloaded: – +. 14-18 Baruch Hirsch St. !. |. >. <<. ++. >= © Copyright SELA Software & Education Labs Ltd.

/=. Bnei Brak 51202 Israel C# 30 Operator Overloading 8 Overriding Equality • When o overloading erloading eq equality. Bnei Brak 51202 Israel . <<=.GetHashCode() () – Ensure that there’s a good distribution of hash values – Ensure that operator== and Equals are in sync © Copyright SELA Software & Education Labs Ltd.C# 30 Operator Overloading 7 What Operators Are Available • The array indexing operator [] cannot be overloaded. new. *=. &=.Equals(b) then a. . >>= • The following operators cannot be overloaded: l d d – =. ->. alit o override erride q and GetHashCode appropriately pp p y Equals – Ensure that if a. is. -=.. &&. ?:. %=.GetHashCode()  == b. |=. but you can define indexers • Compound assignment operators cannot be overloaded (automatic): – +=. ^=. 14-18 Baruch Hirsch St. typeof. 14-18 Baruch Hirsch St. sizeof. || © Copyright SELA Software & Education Labs Ltd.

14-18 Baruch Hirsch St.(binary) (bi ) op_Subtract S bt t == op_Equality != op_Inequality > op GreaterThan op_GreaterThan += op_AdditionAssignment ++ op_Increment I t Conversions + (unary) op_Implicit op_Explicit op UnaryPlus op_UnaryPlus . Bnei Brak 51202 Israel C# 30 Operator Overloading 10 Operator Notes • Compound arithmetic (e (e.g.(unary) op_UnaryNegation © Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St.C# 30 Operator Overloading 9 Operator Names in the CLS Operator Sign + (binary) Operator Name op_Addition . Bnei Brak 51202 Israel . g +=) operators are automatically generated • There’s There s just one increment operator and one decrement operator – Postfix and prefix semantics are automatically implemented • The function call operator p is not available © Copyright SELA Software & Education Labs Ltd.

return c.C# 30 Operator Overloading 11 User-Defined Conversions • Users can define conversions between user-defined types and other types – But not two system types • Conversions are defined as static f functions ti – 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. 14-18 Baruch Hirsch St. t   } p public static implicit operator float(Celsius c) { p p ( ) { return c. } p p p ( p) { public static implicit operator Celsius(float temp) { Celsius c.. Bnei Brak 51202 Israel C# 30 Operator Overloading 12 Conversions Example struct Celsius { { . public static implicit operator Fahrenheit(Celsius c) { return(((c. } } //Fahrenheit struct definition is very similar © Copyright SELA Software & Education Labs Ltd._temp. Bnei Brak 51202 Israel .. c = new Celsius(temp)._temp t ((( t * 9) / 5)   32) * 9) / 5) + 32).

14-18 Baruch Hirsch St.. Bnei Brak 51202 Israel . 14-18 Baruch Hirsch St.C# 30 Operator Overloading 13 Explicit and Implicit Conversions • Declare a conversion explicit if it can cause exceptions or lose information ( (precision) i i ) – An explicit conversion must be invoked via an explicit cast operator • Implicit conversions should not cause any unexpected t d results lt – No exceptions. c = 2. //Implicit int to float.. implicit float to Celsius © Copyright SELA Software & Education Labs Ltd.. Bnei Brak 51202 Israel C# 30 Operator Overloading 14 Sequence of Conversions • 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 float. no precision loss © Copyright SELA Software & Education Labs Ltd. this is a valid sequence: Celsius c = .

14-18 Baruch Hirsch St.C# 30 Operator Overloading 15 Chapter Summary • C# operators are – Static methods – Must have at least one argument of its enclosing type’s yp type yp – Can be explicit or implicit • Some operators are automatic • Beware with redefining equality and defining new conversions © Copyright SELA Software & Education Labs Ltd. Bnei Brak 51202 Israel .