C# Operator Overloading and Type Conversions C#.NET Software Development Version 1.0.

Slides:



Advertisements
Similar presentations
ISBN Chapter 7 Expressions and Assignment Statements.
Advertisements

ISBN Chapter 7 Expressions and Assignment Statements.
All the Operators. Precedence An operator with higher precedence is done earlier (prededes) one with lower precedence –A higher precedence is indicated.
All the Operators. Precedence An operator with higher precedence is done earlier (prededes) one with lower precedence –A higher precedence is indicated.
CS 3850 Lecture 5 Operators. 5.1 Binary Arithmetic Operators Binary arithmetic operators operate on two operands. Register and net (wire) operands are.
ISBN Chapter 7 Expressions and Assignment Statements.
ISBN Chapter 7 Expressions and Assignment Statements.
JavaScript, Third Edition
ISBN Lecture 07 Expressions and Assignment Statements.
Performing Simple Calculations with C# Svetlin Nakov Telerik Corporation
Copyright © 1998 by Addison -Wesley Longman, Inc. 1 Chapter 6 Arithmetic Expressions - Their evaluation was one of the motivations for the development.
1-1 University of Hail College of Computer Science and Engineering Department of computer Science and Software Engineering Course: ICS313: Fundamentals.
Ryan Chu. Arithmetic Expressions Arithmetic expressions consist of operators, operands, parentheses, and function calls. The purpose is to specify an.
Chapter 7 Expressions and Assignment Statements. Copyright © 2007 Addison-Wesley. All rights reserved. 1–2 Arithmetic Expressions Arithmetic evaluation.
CS 363 Comparative Programming Languages Expressions and Assignment Statements.
C H A P T E R S E V E N Expressions and Assignment Statements.
Operators & Overloading Joe Meehean. Expressions Expression composed of operands combined with operators e.g., a + b Operands variables and literals in.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
Chapter 3: Data Types and Operators JavaScript - Introductory.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
Operators Using Java operators An operator takes one or more arguments and produces a new value. All operators produce a value from their.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
C++ Basics Tutorial 6 Operators. What are going to see today? Assignment operator(=) Arithmetic operators(+,-,*,/,%) Compound assignment(+=,-=,*=……..)
Arithmetic Expressions
C Operators. CONTENTS C OPERATORS TYPES OF OPERATOR UNARY BINARY TERNARY ARITHMATIC RELATIONAL LOGICAL.
COMPUTER PROGRAMMING. variable What is variable? a portion of memory to store a determined value. Each variable needs an identifier that distinguishes.
Expressions and Assignment Statements
15-Nov-15 All the Operators. operators.ppt 2 Precedence An operator with higher precedence is done earlier (precedes) one with lower precedence A higher.
ISBN Chapter 7 Expressions and Assignment Statements.
 2008 Pearson Education, Inc. All rights reserved Operator Overloading.
Chapter 7 Expressions and Assignment Statements. Outline Introduction Arithmetic Expressions Overloaded Operators Type Conversions Assignment Statements.
Computing with C# and the.NET Framework Chapter 2 C# Programming Basics ©2003, 2011 Art Gittleman.
ISBN Chapter 7 Expressions and Assignment Statements.
Operator Overloading Week 5.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Java Operator Precedence Operator Meaning Assoc. ===========================================================.
OperatorstMyn1 Operators An operator is something that you feed with one or more values (or expressions, in programming jargon) which yields another value.
What are Operators? Some useful operators to get you started.
ECE 103 Engineering Programming Chapter 4 Operators Herbert G. Mayer, PSU CS Status 6/19/2015 Initial content copied verbatim from ECE 103 material developed.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Programming Principles Operators and Expressions.
CSCI 1100/1202 January 18, Arithmetic Expressions An expression is a combination of operators and operands Arithmetic expressions compute numeric.
ISBN Chapter 7 Expressions and Assignment Statements.
ISBN Chapter 7 Expressions and Assignments Statements.
7-1/27 Chapter 7 Expressions and Assignment Statements Introduction Arithmetic Expressions Overloaded Operators Type Conversions Relational and Boolean.
ECE 103 Engineering Programming Chapter 4 Operators Herbert G. Mayer, PSU Status 6/10/2016 Initial content copied verbatim from ECE 103 material developed.
Operator Overloading.
Expressions and Assignment Statements
7.2 Arithmetic Expressions
Chapter 7: Expressions and Assignment Statements
Operators and Expressions
Expressions and Assignment Statements
C# Operator Overloading and Type Conversions
University of Central Florida COP 3330 Object Oriented Programming
Java Primer 1: Types, Classes and Operators
University of Central Florida COP 3330 Object Oriented Programming
Chapter 7: Expressions and Assignment Statements
Expressions and Assignment Statements
Computing with C# and the .NET Framework
Operators and Expressions
Expressions and Assignment Statements
All the Operators 22-Nov-18.
Expressions and Assignment Statements
All the Operators 4-Dec-18.
C Operators, Operands, Expressions & Statements
Expressions and Assignment Statements
elementary programming
All the Operators 6-Apr-19.
All the Operators 13-Apr-19.
ENERGY 211 / CME 211 Lecture 5 October 1, 2008.
Expressions and Assignment Statements
Presentation transcript:

C# Operator Overloading and Type Conversions C#.NET Software Development Version 1.0

Copyright © by Dennis A. Fairclough all rights reserved. 2 Operator Overloading  Operators are static members of the class or struct  One of the parameters must be of the enclosing (class) type  Overloading operators does not affect their precedence or associativity  Overloading operators does not affect their order of operand evaluation  Some operators require that you overload a counterpart Example: if you overload operator ==, you should overload operator!=  Operators should generally return a new instance of the enclosing class

Copyright © by Dennis A. Fairclough all rights reserved. 3 Operator Return types  C# 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)

Copyright © by Dennis A. Fairclough all rights reserved. 4 C# Operators CategoryExpressionDescription Primary x.m Member access x(...) Method and delegate invocation x[...] Array and indexer access x++ Post-increment x-- Post-decrement new T(...) Object, delegate creation and structure initialization new T[...] Array creation typeof(T) Obtain System.Type object of T checked(x) Evaluate expression in checked context unchecked(x) Evaluate expression in unchecked context Unary +x Identity (Positive) -x Negation !x Logical negation ~x Bitwise negation ++x Pre-increment --x Pre-decrement (T)x Explicitly convert x to type T (Casting)

Copyright © by Dennis A. Fairclough all rights reserved. 5 Multiplicative x * y Multiplication x / y Division x % y Remainder Additive x + y Addition, string concatenation, delegate combination x – y Subtraction, delegate removal Shift x << y Shift left x >> y Shift right Relational and type testing x < y Less than x > y Greater than x <= y Less than or equal x >= y Greater than or equal x is T Return true if x is a T, false otherwise x as T Return x typed as T, or null if x is not a T Equality x == y Equal x != y Not equal Logical AND x & y Integer bitwise AND, boolean logical AND Logical XOR x ^ y Integer bitwise XOR, boolean logical XOR Logical OR x | y Integer bitwise OR, boolean logical OR Conditional AND x && y Evaluates y only if x is true Conditional OR x || y Evaluates y only if x is false Conditional x ? y : z Evaluates y if x is true, z if x is false Assignment x = y Assignment x op = y Compound assignment; supported operators are *= /= %= += -= >= &= ^= |=

Copyright © by Dennis A. Fairclough all rights reserved. 6 Order of Operand Evaluation  What’s the output? using System; class T { static void Main() { int i = 6; Console.WriteLine(i++ + i++ * i); } (See OrderOfEvaluation Demo)

Copyright © by Dennis A. Fairclough all rights reserved. 7 Overloadable Operators  Unary operators + - ! ~ true false  Binary arithmetic operators + - * / % ^ & | >  Note: && and || are overloaded implicitly when you overload & and |  Binary comparison operators == != >=  Binary conditional operators true false  Conversions Any conversion (explicit or implicit) between the enclosing type and another type.

Copyright © by Dennis A. Fairclough all rights reserved. 8 Non-Overloadable Operators  =. ?: -> new as is sizeof typeof checked unchecked  += -= *= /= %= &= |= ^= >= && ||  Assignment operators are overloaded implicitly when you overload their binary counterpart

Copyright © by Dennis A. Fairclough all rights reserved. 9 Unary Operators  Operators + - ! ~  Operand must be of the enclosing type public static IntWrapper operator+(IntWrapper rhs) { return new IntWrapper(rhs._value); } (See OperatorOverloading Demo)

Copyright © by Dennis A. Fairclough all rights reserved. 10 Unary Operators ++ and --  Remember C++ syntax? public T operator++(); public 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 In other words, the compiler just handles it!  Important: 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

Copyright © by Dennis A. Fairclough all rights reserved. 11 Unary operator– int and T Example public class T { private int i; private int i; public static T operator--(T t) public static T operator--(T t) { // Make new reference // Make new reference T ret = new T(); T ret = new T(); ret.i = t.i-1; ret.i = t.i-1; return ret; return ret; }} public class int { private int i; private int i; public static int operator--(int t) public static int operator--(int t) { // Make new reference // Make new reference int ret = new int(); int ret = new int(); ret.i = t.i-1; ret.i = t.i-1; return ret; return ret; }}

Copyright © by Dennis A. Fairclough all rights reserved. 12 Binary Operator 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 of the enclosing type  You may overload as many times as you like with different parameter types  You may return any type  No “ref” or “out” parameters (See OperatorOverloadingBinary Demo)

Copyright © by Dennis A. Fairclough all rights reserved. 13 Binary Arithmetic Operators  Operators + - * / % ^ & | >  At least one of the parameters must be of the enclosing type // 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) { return new Class1(lhs.X + rhs); } // int + Class1 public static Class1 operator+(int lhs, Class1 rhs) { return new Class1(rhs.X + lhs); }

Copyright © by Dennis A. Fairclough all rights reserved. 14 Binary operators >> and <<  First parameter must be the enclosing type  Second parameter must be an integer // overloaded 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); }

Copyright © by Dennis A. Fairclough all rights reserved. 15 Binary Comparison Operators  Operators == != >=  Should return bool public static bool operator<(Class2 lhs, Class2 rhs) { return new Class2(lhs.i < rhs.i); }

Copyright © by Dennis A. Fairclough all rights reserved. 16 Operators == and !=  Overloading == requires overloading the != why?  Why have both == and.Equals() ? Some.NET languages don’t allow operator overloading You should define operator== in terms of.Equals() It could be bad to do one and not the other

Copyright © by Dennis A. Fairclough all rights reserved. 17 Binary Conditional Operators  Operators true false  You must overload these if you want short-circuiting behavior and you have overloaded operator& and operator|  The true/false operators must be overloaded together  operator true : returns true if the class represents true, otherwise returns false  operator false : returns true if the class represents false, otherwise returns false

Copyright © by Dennis A. Fairclough all rights reserved. 18 Using Operators && and ||  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 using operator false or operator true (respectively) If you overload & and |, you cannot use && or || unless you overload true and false  Why not just use conversion operator bool? The compiler won’t let you. (They were asleep when they designed this)

Copyright © by Dennis A. Fairclough all rights reserved. 19 Conversion 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)

Copyright © by Dennis A. Fairclough all rights reserved. 20 User-Defined Conversions  “A conversion enables an expression of one type to be treated as another type.” – C# 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 an 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)

Copyright © by Dennis A. Fairclough all rights reserved. 21 Finding the Best Conversion  Finds the set of all classes and base classes involved  Determines which user-defined conversions are applicable  Finds 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

Copyright © by Dennis A. Fairclough all rights reserved. 22 Performing the conversion  If required, converts 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

Copyright © by Dennis A. Fairclough all rights reserved. 23 Conversion Guidelines  Conversions that would “narrow” your object should be made explicit  Conversions that would “widen” your object can be made implicit

Copyright © by Dennis A. Fairclough all rights reserved. 24 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.

Copyright © by Dennis A. Fairclough all rights reserved. 25 What did you learn?  ??