OPERATORS & CASTS

Operators
Type Safety
Comparing Objects
Operator Overloading
User-Defined Casts
Operators
CATEGORY (BY
                  OPERATOR(S)                             ASSOCIATIVITY
PRECEDENCE)

                  x.y f(x) a[x] x++ x-- new() typeof ()
Primary                                                   left
                  default checked unchecked delegate


Unary             + - ! ~ ++x --x (T)x                    left

Multiplicative    * / %                                   left
Additive          + -                                     left
Shift             << >>                                   left
Relational        < > <= >= is as                         left
Equality          == !=                                   right
Logical AND       &                                       left
Logical XOR       ^                                       left
Logical OR        |                                       left
Conditional AND   &&                                      left
Conditional OR    ||                                      left
Null Coalescing   ??                                      left
Ternary           ?:                                      right

Assignment        = *= /= %= += -= <<= >>= &= ^= |= =>    right
Conditional Operator
 The conditional operator (?:) returns one of two values
  depending on the value of a Boolean expression.
 Following is the syntax for the conditional operator.
     condition ? first_expression : second_expression;
 The condition must evaluate to true or false. If condition is
  true, first_expression is evaluated and becomes the
  result. If condition is false, second_expression is
  evaluated and becomes the result.
The Checked and Unchecked
Operator
 The checked keyword is used to explicitly enable
  overflow checking for integral-type arithmetic operations
  and conversions.
   Ex:
       byte b=255;
       b+=5; //What is the value of is
        //The value of b here b?4
By default, these non-constant expressions are not
checked for overflow at run time either, and they do not
raise overflow exceptions.
 If you mark a block of code as checked, the CLR will
enforce overflow checking, and throw OverflowException
if any overflow occurs.
If you want to suppress overflow checking, you can
mark the code as unchecked
New Operators in C#
 The is Operator
   Checks if an object is compatible with a given type.
 The as Operator
   The as operator is used to perform certain types of
    conversions between compatible reference types.
 Null Coalescing Operator(??)
     The ?? operator is called the null-coalescing operator and is
      used to define a default value for a nullable value types as
      well as reference types.
Type Conversion
 Type Safety
   C# is a Strongly Typed language, this means that
    datatypes are not always seamlessly interchangeable.
 Type Conversion
   Converting from one type to another type is called type
    conversion.
     Implicit Conversion
       No special syntax is required because the conversion is
        type safe and no data will be lost.
     Explicit Conversion
       Explicit conversions require a cast operator. Casting is
        required when information might be lost in the conversion,
        or when the conversion might not succeed for other
        reasons.
Boxing
 Boxing
  Boxing is the process of converting a value type to the type
   object or to any interface type implemented by this value type.
  When the CLR boxes a value type, it wraps the value inside a
   System.Object and stores it on the managed heap. Unboxing
   extracts the value type from the object.
  Ex:
     int i = 123; // The following line boxes i.
     object o = i;
Unboxing
 Unboxing
  Unboxing is an explicit conversion from the type object to a
   value type or from an interface type to a value type that
   implements the interface.
  The following statements demonstrate both boxing and unboxing
   operations
        int i = 123; // a value type
        object o = i; // boxing
        int j = (int)o; // unboxing
Comparing Objects for Equality
 The mechanisms of object equality are different
  depending on whether you are comparing
  Reference types (instances of classes) or Value
  types (primitive types or instances of structs).
 System.Object defines three different methods for
  comparing objects.
   ReferenceEquals(ref1,ref2)
     It is a static method that tests whether two references refer to
      the same instance of a class.
   The Virtual Equals(Object)
     It is also for comparing references, however you can override
      it in your own class because it is virtual
Comparing Objects for Equality
 The static Equals(Object, Object)
   Determines whether the specified object instances are
   considered equal.
 Comparison Operator (==)
   For predefined value types, the equality operator (==)
    returns true if the values of its operands are equal,
    false otherwise.
   For reference types other than string, == returns true if
    its two operands refer to the same object.
   For the string type, == compares the values of the
    strings.
Operator Overloading
   C# allows user-defined types to overload operators
   by defining static member functions using the
   operator keyword.
  Which Operators You Can Overload
Operators                   Overloadability
                                          These unary operators can be
+, -, !, ~, ++, --, true, false
                                          overloaded.
                                          These binary operators can be
+, -, *, /, %, &, |, ^, <<, >>
                                          overloaded.
                                          The comparison operators can be
==, !=, <, >, <=, >=                      overloaded (but see the note that
                                          follows this table).
  The comparison operators, if overloaded, must be overloaded in pairs; that is,
  if == is overloaded, != must also be overloaded. The reverse is also true, and
  similar for < and >, and for <= and >=.
Operator Overloading
 Operator overloading permits user-defined operator
  implementations to be specified for operations
  where one or both of the operands are of a user-
  defined class or struct type.
 C# use the operator keyword to overload a built-in
  operator or to provide a user-defined conversion in
  a class or struct declaration.
 Syntax:
     public static result-type operator unary-operator ( op-type
      operand ) {}
     public static result-type operator binary-operator ( op-type
      operand, op-type2 operand2 ) {}
Operator Overloading
 Ex:
        class Fraction {
        int num, den;
        public Fraction(int num, int den) { this.num = num;
        this.den = den; }
        public static Fraction operator +(Fraction a, Fraction b)
        {
        return new Fraction(a.num * b.den + b.num * a.den, a.den
        * b.den);
        }}
User-Defined Casts
 Implicit Conversion
 The implicit keyword is used to declare an implicit user-
  defined type conversion operator.
 Use it to enable implicit conversions between a user-defined
  type and another type, if the conversion is guaranteed not to
  cause a loss of data.
   Syntax:
     public static implicit operator conv-type-out ( conv-type-in
      operand ) {}
   Ex:
      class MyType {
      public static implicit operator int(MyType m) {
      // code to convert from MyType to int }
      }
 Implicit conversion operators can be called implicitly, without
  being specified by explicit casts in the source code.
User-Defined Casts
 Explicit Conversion
 The explicit keyword is used to declare an explicit user-
  defined type conversion operator.
 Syntax:
     public static explicit operator conv-type-out ( conv-type-in
        operand ) {}
 Ex:
     class MyType {
     public static explicit operator MyType(int i) {
     // code to convert from int to MyType } }
 Unlike implicit conversion, explicit conversion operators must
  be invoked via a cast.
 Ex:
        int i;
        MyType x = (MyType)i; // int-to-MyType requires cast

Operators & Casts

  • 1.
    OPERATORS & CASTS Operators TypeSafety Comparing Objects Operator Overloading User-Defined Casts
  • 2.
    Operators CATEGORY (BY OPERATOR(S) ASSOCIATIVITY PRECEDENCE) x.y f(x) a[x] x++ x-- new() typeof () Primary left default checked unchecked delegate Unary + - ! ~ ++x --x (T)x left Multiplicative * / % left Additive + - left Shift << >> left Relational < > <= >= is as left Equality == != right Logical AND & left Logical XOR ^ left Logical OR | left Conditional AND && left Conditional OR || left Null Coalescing ?? left Ternary ?: right Assignment = *= /= %= += -= <<= >>= &= ^= |= => right
  • 3.
    Conditional Operator  Theconditional operator (?:) returns one of two values depending on the value of a Boolean expression.  Following is the syntax for the conditional operator.  condition ? first_expression : second_expression;  The condition must evaluate to true or false. If condition is true, first_expression is evaluated and becomes the result. If condition is false, second_expression is evaluated and becomes the result.
  • 4.
    The Checked andUnchecked Operator  The checked keyword is used to explicitly enable overflow checking for integral-type arithmetic operations and conversions.  Ex: byte b=255; b+=5; //What is the value of is //The value of b here b?4 By default, these non-constant expressions are not checked for overflow at run time either, and they do not raise overflow exceptions.  If you mark a block of code as checked, the CLR will enforce overflow checking, and throw OverflowException if any overflow occurs. If you want to suppress overflow checking, you can mark the code as unchecked
  • 5.
    New Operators inC#  The is Operator  Checks if an object is compatible with a given type.  The as Operator  The as operator is used to perform certain types of conversions between compatible reference types.  Null Coalescing Operator(??)  The ?? operator is called the null-coalescing operator and is used to define a default value for a nullable value types as well as reference types.
  • 6.
    Type Conversion  TypeSafety  C# is a Strongly Typed language, this means that datatypes are not always seamlessly interchangeable.  Type Conversion  Converting from one type to another type is called type conversion.  Implicit Conversion  No special syntax is required because the conversion is type safe and no data will be lost.  Explicit Conversion  Explicit conversions require a cast operator. Casting is required when information might be lost in the conversion, or when the conversion might not succeed for other reasons.
  • 7.
    Boxing  Boxing Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type.  When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap. Unboxing extracts the value type from the object.  Ex: int i = 123; // The following line boxes i. object o = i;
  • 8.
    Unboxing  Unboxing Unboxing is an explicit conversion from the type object to a value type or from an interface type to a value type that implements the interface.  The following statements demonstrate both boxing and unboxing operations int i = 123; // a value type object o = i; // boxing int j = (int)o; // unboxing
  • 9.
    Comparing Objects forEquality  The mechanisms of object equality are different depending on whether you are comparing Reference types (instances of classes) or Value types (primitive types or instances of structs).  System.Object defines three different methods for comparing objects.  ReferenceEquals(ref1,ref2)  It is a static method that tests whether two references refer to the same instance of a class.  The Virtual Equals(Object)  It is also for comparing references, however you can override it in your own class because it is virtual
  • 10.
    Comparing Objects forEquality  The static Equals(Object, Object)  Determines whether the specified object instances are considered equal.  Comparison Operator (==)  For predefined value types, the equality operator (==) returns true if the values of its operands are equal, false otherwise.  For reference types other than string, == returns true if its two operands refer to the same object.  For the string type, == compares the values of the strings.
  • 11.
    Operator Overloading  C# allows user-defined types to overload operators by defining static member functions using the operator keyword.  Which Operators You Can Overload Operators Overloadability These unary operators can be +, -, !, ~, ++, --, true, false overloaded. These binary operators can be +, -, *, /, %, &, |, ^, <<, >> overloaded. The comparison operators can be ==, !=, <, >, <=, >= overloaded (but see the note that follows this table). The comparison operators, if overloaded, must be overloaded in pairs; that is, if == is overloaded, != must also be overloaded. The reverse is also true, and similar for < and >, and for <= and >=.
  • 12.
    Operator Overloading  Operatoroverloading permits user-defined operator implementations to be specified for operations where one or both of the operands are of a user- defined class or struct type.  C# use the operator keyword to overload a built-in operator or to provide a user-defined conversion in a class or struct declaration.  Syntax:  public static result-type operator unary-operator ( op-type operand ) {}  public static result-type operator binary-operator ( op-type operand, op-type2 operand2 ) {}
  • 13.
    Operator Overloading  Ex: class Fraction { int num, den; public Fraction(int num, int den) { this.num = num; this.den = den; } public static Fraction operator +(Fraction a, Fraction b) { return new Fraction(a.num * b.den + b.num * a.den, a.den * b.den); }}
  • 14.
    User-Defined Casts  ImplicitConversion  The implicit keyword is used to declare an implicit user- defined type conversion operator.  Use it to enable implicit conversions between a user-defined type and another type, if the conversion is guaranteed not to cause a loss of data.  Syntax:  public static implicit operator conv-type-out ( conv-type-in operand ) {}  Ex: class MyType { public static implicit operator int(MyType m) { // code to convert from MyType to int } }  Implicit conversion operators can be called implicitly, without being specified by explicit casts in the source code.
  • 15.
    User-Defined Casts  ExplicitConversion  The explicit keyword is used to declare an explicit user- defined type conversion operator.  Syntax:  public static explicit operator conv-type-out ( conv-type-in operand ) {}  Ex:  class MyType {  public static explicit operator MyType(int i) {  // code to convert from int to MyType } }  Unlike implicit conversion, explicit conversion operators must be invoked via a cast.  Ex: int i; MyType x = (MyType)i; // int-to-MyType requires cast

Editor's Notes

  • #3 Visit http://msdn.microsoft.com/en-us/library/6a71f45d%28v=vs.80%29.aspx for more information on operators
  • #16 Referhttp://msdn.microsoft.com/en-us/library/xhbhezf4(v=VS.100).aspxhttp://msdn.microsoft.com/en-us/library/aa691303(v=VS.71).aspx