Presentation is loading. Please wait.

Presentation is loading. Please wait.

C# Operator Overloading and Type Conversions

Similar presentations


Presentation on theme: "C# Operator Overloading and Type Conversions"— Presentation transcript:

1 C# Operator Overloading and Type Conversions
CNS 3260 C# .NET Software Development

2 Operator Overloading Unary operators: Binary operators:
Are members of the class or struct Take single arguments Binary operators: Are public static take two arguments One of the parameters must be of the enclosing type Use the operator keyword followed by the operator you want to overload Some operators require that you overload a counterpart Example: if you overload operator==, you must overload operator!=

3 Overloadable Operators
+ - ! ~ (pre and post) + - * / % ^ << >> == != < > <= >= & | [ ] is done through indexers

4 NonOverloadables = . ?: -> new is sizeof typeof
+= -= *= /= %= &= |= ^= <<= >>= Assignment operators are made implicitly when you overload their binary counterpart

5 Precedence Type Operators Primary
. () [] new typeof checked unchecked Unary + - ! ~ ++x --x (T)x Multiplicative * / % Additive + - Shift << >> Relational and Type Testing < > <= >= as is Equality == != Logical And & Logical Xor ^ Logical Or | Conditional And && Conditional Or || Conditional (ternary) ?: Assignment = *= /= %= += -= <<= >>= &= ^= |=

6 Associativity Determines the order in which the operation is performed when within an expression with operators of the same precedence Overloading operators does not affect their precedence or associativity Overloading operators does not affect the order of operand evaluation

7 Operand order of Evaluation
What’s the output? using System; class T { static void Main() int i = 6; Console.WriteLine(i++ + i++ * i); } (See OrderOfEvaluation Demo)

8 Logical or Bitwise? Operators &, | and ^ are listed as Logical operators Logical because the bit pattern of bool is undefined, but the behavior of &, | and ^ between bool types is defined. Defined only for integral types and bool Integral types: Perform bitwise operations Bool types: Returns the logical result of the operation

9 Conditional && and || Performed between bool operands
“but only evaluates its second operand if necessary “ – MSDN Short-Circuiting operators

10 Binary Operator Syntax
// Class1 + Class1 public static Class1 operator+(Class1 lhs, Class1 rhs) { return new Class1(lhs.X + rhs.X); } // Class1 + int public static Class1 operator+(Class1 lhs, int rhs) // int + Class1 public static Class1 operator+(int lhs, Class1 rhs)

11 Binary Considerations
At least one parameter must be of the enclosing type. Be aware of what you are returning You will almost always want to return a new instance You may overload as many times as you like with different parameters You may return any type No “ref” or “out” parameters (See OperatorOverloadingBinary Demo)

12 Operators == and != Overloading one requires the other
Why == and .Equals()? Some .NET languages don’t allow operator overloading Define operator== in terms of .Equals() Would be bad to do one and not the other (See OperatorOverloadingEquality Demo)

13 Operators ++ and -- Remember C++ syntax?
public static T operator++(); public static T operator++(int); In C#, one operator overload handles both cases Here’s how it works: Whatever you return is the new value of your variable When a post operator is called, the old object (or reference) is given to the expression When a pre operator is called, the new object (or reference) is given to the expression To get the behavior you expect, you must create a new object and return it If you modify the original value, it will affect the post operator accordingly

14 operator-- Example (See OperatorOverloadingIncrement Demo)
public class T { private int i; public static T operator--(T t) { // Make new reference T ret = new T(); ret.i = t.i-1; return ret; } (See OperatorOverloadingIncrement Demo)

15 Shift operators >> and <<
First parameter must be the enclosing type Second parameter must be an integer You may return anything you want // shift operator public static Class2 operator<<(Class2 c2, int shl) { return new Class2(c2.i << shl); } // this won't compile public static Class2 operator<<(Class2 c2, Class2 shl) return new Class2(1000);

16 Unary operators + - ! ~ Argument must be of the enclosing type
public static Class2 operator~(Class2 c2) { return new Class2(~c2.i); }

17 Operator Return types Note from the standard:
“While it is possible for a user-defined operator to perform any computation it pleases, implementations that produce results other than those that are intuitively expected are strongly discouraged. For example, an implementation of operator == should compare the two operands for equality and return an appropriate bool result.” – C# standard (p 126)

18 Implicit Conversions Identity conversions Implicit numeric conversions
Implicit enumeration conversions Implicit reference conversions Boxing conversions Implicit constant expression conversions User-defined implicit conversions

19 Explicit Conversions All implicit conversions
Explicit numeric conversions Explicit enumeration conversions Explicit reference conversions Explicit interface conversions Unboxing conversions User-defined explicit conversions

20 User-Defined Conversions
“A conversion enables an expression of one type to be treated as another type.” – The Standard (p 113) A User-Defined Conversion between types T and S is allowed when: S and T are different types Either S or T is the class or struct type in which the operator declaration takes place Neither S nor T is object or an interface-type T is not a base class of S, and S is not a base class of T Conversions are allowed both to and from the enclosing type You must state if the conversions is implicit or explicit Explicit conversions require a cast Implicit conversions don’t require a cast (See UserDefinedConversion demo)

21 Finding the Best Conversion
Find the set of all classes and base classes involved Determine which user-defined conversions are applicable Find the conversion for which both the operand and the result match closest Searches for the best match of the operand type first Searches for the best match of the result last

22 Performing the conversion
If required, convert the operand from its source type to the operand type using standard conversions. Perform the user-defined conversion If required, convert the result to the target type using standard conversions

23 Conversion Guidlines Don’t throw exceptions in implicit casts
Not a rule, just a preference If you might throw, make the conversion explicit Conversions that would “narrow” your object should be made explicit Conversions that would “widen” your object can be made implicit

24 What’s the output? using System; class T {
public static implicit operator int(T t) Console.WriteLine("operator int"); return 5; } static void Main() Console.WriteLine(new T());

25 Conversion Vs. Operator
If both an overloaded operator and a type conversion exists between a user type and a standard type, the operator will be used and not the conversion.

26 Which gets called? using System; class T {
public static implicit operator int(T t) Console.WriteLine("operator int"); return 5; } public static T operator+(T l, T r) return new T(); public static T operator+(T l, int i) static void Main() Console.WriteLine((object)(new T() + 8));

27 Which gets called? using System; class T {
public static implicit operator int(T t) Console.WriteLine("operator int"); return 5; } public static T operator+(T l, T r) return new T(); static void Main() Console.WriteLine((object)(new T() + 8));

28 Short-Circuiting (again)
And operation: as soon as a false operand is encountered, the operation returns false and stops Or operation: as soon as a true operand is encountered, the operation returns true and stops && and || are short-circuiting logical (conditional) operators & and | are non-short-circuiting logical operators (See ShortCircuiting Demo Parts 1 and 2)

29 Operator bool Allows your class to be used in conditional statements, including &&, ||, if, while, etc. public static implicit operator bool(Class1 c) { return c.boolValue } (See ShortCircuiting Demo Part 3)

30 operators & and | Normal binary operators
Use them to perform non-short-circuiting operations or bitwise operations Return the calling type and overload operator bool When you overload these operators, operator&& and operator|| get overloaded implicitly for you public static Class1 operator&(Class1 lhs, Class1 rhs) { return new Class1(lhs && rhs); } public static implicit operator bool(Class1 c) { return c.BoolValue; }

31 Using operators && and ||
operator & is seen as a version of && operator | is seen as a version of || operator & and operator | are called conditionally when using && and || (respectively) operator & is only called if the first operand is true operator | is only called if first operand is false When using && or || the first operand is evaluated used operator false or operator true (respectively) Why not just use operator bool? The compiler won’t let you. (They were asleep when they designed this)

32 operators true and false
You must overload these if you want short-circuiting behavior and you have overloaded operator& and operator| These operators must be overloaded together (if you overload one, you must overload the other) operator true: returns true if the class represents true, otherwise returns false operator false: returns true if the class represents false, otherwise returns false (See ShortCircuiting Demo Parts 4 and 5)


Download ppt "C# Operator Overloading and Type Conversions"

Similar presentations


Ads by Google