operators & casts

Click here to load reader

Upload: raghuveer-guthikonda

Post on 18-Jan-2015

318 views

Category:

Technology


2 download

DESCRIPTION

 

TRANSCRIPT

  • 1. OPERATORS & CASTSOperatorsType SafetyComparing ObjectsOperator OverloadingUser-Defined Casts

2. OperatorsCATEGORY (BYOPERATOR(S) ASSOCIATIVITYPRECEDENCE)x.y f(x) a[x] x++ x-- new() typeof ()Primary leftdefault checked unchecked delegateUnary + - ! ~ ++x --x (T)xleftMultiplicative* / % leftAdditive+ - leftShift > leftRelational< > = is as leftEquality== != rightLogical AND & leftLogical XOR ^ leftLogical OR| leftConditional AND &&leftConditional OR||leftNull Coalescing ??leftTernary ?:rightAssignment= *= /= %= += -= = &= ^= |= =>right 3. Conditional Operator The conditional operator (?:) returns one of two valuesdepending 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 istrue, first_expression is evaluated and becomes theresult. If condition is false, second_expression isevaluated and becomes the result. 4. The Checked and UncheckedOperator The checked keyword is used to explicitly enableoverflow checking for integral-type arithmetic operationsand conversions. Ex: byte b=255; b+=5; //What is the value of is//The value of b here b?4By default, these non-constant expressions are notchecked for overflow at run time either, and they do notraise overflow exceptions. If you mark a block of code as checked, the CLR willenforce overflow checking, and throw OverflowExceptionif any overflow occurs.If you want to suppress overflow checking, you canmark the code as unchecked 5. 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 ofconversions between compatible reference types. Null Coalescing Operator(??) The ?? operator is called the null-coalescing operator and isused to define a default value for a nullable value types aswell as reference types. 6. Type Conversion Type Safety C# is a Strongly Typed language, this means thatdatatypes are not always seamlessly interchangeable. Type Conversion Converting from one type to another type is called typeconversion. Implicit Conversion No special syntax is required because the conversion istype safe and no data will be lost. Explicit Conversion Explicit conversions require a cast operator. Casting isrequired when information might be lost in the conversion,or when the conversion might not succeed for otherreasons. 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 operationsint i = 123; // a value typeobject o = i; // boxingint j = (int)o; // unboxing 9. Comparing Objects for Equality The mechanisms of object equality are differentdepending on whether you are comparingReference types (instances of classes) or Valuetypes (primitive types or instances of structs). System.Object defines three different methods forcomparing objects. ReferenceEquals(ref1,ref2) It is a static method that tests whether two references refer tothe same instance of a class. The Virtual Equals(Object) It is also for comparing references, however you can overrideit in your own class because it is virtual 10. 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 ifits two operands refer to the same object. For the string type, == compares the values of thestrings. 11. Operator Overloading C# allows user-defined types to overload operators by defining static member functions using the operator keyword. Which Operators You Can OverloadOperators OverloadabilityThese unary operators can be+, -, !, ~, ++, --, true, falseoverloaded.These binary operators can be+, -, *, /, %, &, |, ^, overloaded.The comparison operators can be==, !=, , =overloaded (but see the note thatfollows 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, andsimilar for < and >, and for =. 12. Operator Overloading Operator overloading permits user-defined operatorimplementations to be specified for operationswhere one or both of the operands are of a user-defined class or struct type. C# use the operator keyword to overload a built-inoperator or to provide a user-defined conversion ina class or struct declaration. Syntax: public static result-type operator unary-operator ( op-typeoperand ) {} public static result-type operator binary-operator ( op-typeoperand, 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 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-definedtype and another type, if the conversion is guaranteed not tocause a loss of data. Syntax: public static implicit operator conv-type-out ( conv-type-inoperand ) {} Ex:class MyType {public static implicit operator int(MyType m) {// code to convert from MyType to int }} Implicit conversion operators can be called implicitly, withoutbeing specified by explicit casts in the source code. 15. 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-inoperand ) {} Ex: class MyType { public static explicit operator MyType(int i) { // code to convert from int to MyType } } Unlike implicit conversion, explicit conversion operators mustbe invoked via a cast. Ex:int i;MyType x = (MyType)i; // int-to-MyType requires cast