Operators, Type Safety

download Operators, Type Safety

of 45

Transcript of Operators, Type Safety

  • 8/6/2019 Operators, Type Safety

    1/45

    Operators and Type Safety

    Prepared By:

    Esha Batish

    Lecture No-28

    Date-02-05-2011

  • 8/6/2019 Operators, Type Safety

    2/45

    Operators in C#

    Operators are used to manipulate data.

    Although most of C# s operators familiar to

    C and C++.The operators supported by C# are:

    Arithmetic + * / % Logical &|^ ~ && || !

    String concatenation +

    Increment and decrement ++

    Bit shifting >

    Comparison == != < > =

  • 8/6/2019 Operators, Type Safety

    3/45

    Assignment = += -= *= /= %= &= |= ^=

    = Member access (for objects and structs) .

    Indexing (for arrays and indexers) []

    Cast ()

    Conditional (the ternary operator) ?:

    Delegate

    Object creation new Type information sizeof, is, typeof, as

  • 8/6/2019 Operators, Type Safety

    4/45

    Overflow exception control checked

    unchecked Indirection and address []

    Namespace alias qualifier

    :: Null coalescing operator ??

    Note that four specific operators (sizeof, *, ->,

    and &, however, are available only in unsafecode (code that bypasses C#s type-safety

    checking).

  • 8/6/2019 Operators, Type Safety

    5/45

    Shortcut Operator Equivalent To

    x++, ++x x = x + 1 x--, --x x = x 1

    x += y x = x + y

    x -= y x = x - y

    x *= y x = x * y

    x /= y x = x / y

    x %= y x = x % y

    x >>= y x = x >> y x

  • 8/6/2019 Operators, Type Safety

    6/45

    checked and unchecked operators

    If you mark a block of code as checked, theCLR will enforce overflow checking, and

    throw an OverflowException if an overflow

    occurs.

    Consider the following code:

    byte b = 255;

    b++;Console.WriteLine(b.ToString());

    Contd..

  • 8/6/2019 Operators, Type Safety

    7/45

    The byte data type can hold values only in the

    range 0 to 255, so incrementing the value of bcauses an overflow. So its good to use

    checked.

    byte b = 255; checked

    {

    b++; }

    Console.WriteLine(b.ToString());

  • 8/6/2019 Operators, Type Safety

    8/45

    When you try to run this code, you will get anerror message like this:Unhandled Exception:System.OverflowException:Arithmeticoperation resulted in an overflow atWrox.ProCSharp.Basics.OverflowTest.Main(S

    tring[] args) If you want to suppress overflow checking,

    you can mark the code as unchecked. In thiscase, no exception will be raised, but you will

    lose data because the byte type cannot holda value of 256, the overflowing bits will bediscarded, and your b variable will hold avalue of zero (0).

  • 8/6/2019 Operators, Type Safety

    9/45

    byte b = 255;

    unchecked {

    b++;

    }

    Console.WriteLine(b.ToString());

    Note that unchecked is the default behavior.

  • 8/6/2019 Operators, Type Safety

    10/45

    The is operator

    The is operator allows you to check whether anobject is compatible with a specific type. The

    phrase is compatible means that an object

    either is of that type or is derived from thattype. For example, to check whether a variable

    is compatible with the object type, you could

    use the following bit of code:

    int i = 10;

    if (i is object)

  • 8/6/2019 Operators, Type Safety

    11/45

    {

    Console.WriteLine("i is an object");

    }

    int , like all C# data types, inherits from object

    ,therefore, the expression i is object willevaluate to true in this case.

  • 8/6/2019 Operators, Type Safety

    12/45

    The as operator

    The as operator is used to perform explicit typeconversions of reference types. If the typebeing converted is compatible with thespecified type, conversion is performed

    successfully. However, if the types areincompatible, the as operator returns the valuenull .

    object o1 = "Some String";

    object o2 = 5;

    string s1 = o1 as string; // s1 = "Some String"

    string s2 = o2 as string; // s2 = null

  • 8/6/2019 Operators, Type Safety

    13/45

    The as operator allows you to perform a safe

    type conversion in a single step without theneed to first test the type using the is operator

    and then perform the conversion.

    The sizeof operator:

    You can determine the size (in bytes) using the

    sizeof operator:

    Console.WriteLine(sizeof(int));

  • 8/6/2019 Operators, Type Safety

    14/45

    This will display the number 4 , because an int

    is 4 bytes long. If you are using the sizeof operator with complex types (and not primitive

    types), you will need to block the code within

    an unsafe block as illustrated here:

    unsafe

    {

    Console.WriteLine(sizeof(Customer)); }

  • 8/6/2019 Operators, Type Safety

    15/45

    The typeof operator

    The typeof operator returns a System.Typeobject representing a specified type.

    For example,typeof(string) will return a Type

    object representing the System.String type.This is useful when you want to find out

    information about an object dynamically.

  • 8/6/2019 Operators, Type Safety

    16/45

    Nullable Types and Operators

    Looking at the Boolean type, you have only atrue or false value that you can assign to this

    type. However, what if you wanted to define

    the value of the type as undefined?

    int? a = null;

    int? b = a + 4; // b = null

    int? c = a * 5; // c = null However, when comparing nullable types, if

    only one of the operands is null , the

    comparison will always equate to false .

  • 8/6/2019 Operators, Type Safety

    17/45

    int? a = null;

    int? b = -5; if (a > = b)

    Console.WriteLine("a > = b");

    else

    Console.WriteLine("a < b");

    The possibility of a null value means that you

    cannot freely combine nullable and non-nullable types in an expression.

  • 8/6/2019 Operators, Type Safety

    18/45

    Nullable Typess Characteristics

    Nullable types represent value-type variablesthat can be assigned the value of null. You

    cannot create a nullable type based on a

    reference type. (Reference types alreadysupport the null value.)

    The syntax T? is shorthand for

    System.Nullable, where T is a value type.

    Assign a value to a nullable type in the same

    way as for an ordinary value type, for example

    int? x = 10; or double? d = 4.108;

  • 8/6/2019 Operators, Type Safety

    19/45

    Use the System.Nullable.GetValueOrDefaultproperty to return either the assigned value, or thedefault value for the underlying type if the valueis null, for example int j =x.GetValueOrDefault();

    Use the HasValue and Value read-only propertiesto test for null and retrieve the value.

    The HasValueproperty returns true if the variablecontains a value, or false if it is null.

    The Valueproperty returns a value if one isassigned, otherwise aSystem.InvalidOperationException is thrown.

  • 8/6/2019 Operators, Type Safety

    20/45

    The default value for a nullable type variable

    sets HasValue to false. The Value isundefined.

    Nested nullable types are not allowed.

  • 8/6/2019 Operators, Type Safety

    21/45

    class NullableExample

    {

    static void Main()

    {

    int? num = null;if (num.HasValue == true)

    {

    Console.WriteLine("num = " + num.Value);}

    else

  • 8/6/2019 Operators, Type Safety

    22/45

    {

    Console.WriteLine("num = Null");}

    //y is set to zero

    int y = num.GetValueOrDefault();

    // num.Value throws

    //InvalidOperationException if num.HasValue

    is //false

  • 8/6/2019 Operators, Type Safety

    23/45

    try

    {y = num.Value;

    }

    catch (System.InvalidOperationException e){

    Console.WriteLine(e.Message);

    }}

    }

  • 8/6/2019 Operators, Type Safety

    24/45

    Here is the output

    num = Null

    Nullable object must have a value.

  • 8/6/2019 Operators, Type Safety

    25/45

    The null Coalescing operator

    The null coalescing operator ( ?? ) provides ashorthand mechanism to cater to the possibilityof null values when working with nullable andreference types. The operator is placed

    between two operands the first operandmust be a nullable type or reference type, andthe second operand must be of the same typeas the first or of a type that is implicitlyconvertible to the type of the first operand. Thenull coalescing operator evaluates as follows:

  • 8/6/2019 Operators, Type Safety

    26/45

    If the first operand is not null , then the overallexpression has the value of the first operand.

    If the first operand is null , then the overallexpression has the value of the secondoperand.

    int? a = null; int b;

    b = a ?? 10; // b has the value 10

    a = 3 ; b = a ?? 10; // b has the value 3

  • 8/6/2019 Operators, Type Safety

    27/45

    If the second operand cannot be implicitly

    converted to the type of the first operand, acompile - time error is generated.

  • 8/6/2019 Operators, Type Safety

    28/45

    Operator Precedence

    Group Operators Primary () . [] x++ x-- new typeof sizeof

    checked unchecked

    Unary + ! ~ ++x --x and casts Multiplication * / %

    /division

    Addition + -

    /subtraction

    Bitwise shift operators >

  • 8/6/2019 Operators, Type Safety

    29/45

    Relational < >= is as

    Comparison == != Bitwise AND &

    Bitwise XOR ^

    Bitwise OR | Boolean AND &&

    Boolean OR ||

    Conditional operator ?:

    Assignment = += -= *= /= %= &=

    |= ^= = >>>=

    In

  • 8/6/2019 Operators, Type Safety

    30/45

    Type Safety

    The Intermediate Language (IL) enforcesstrong type safety upon its code. Strong typing

    enables many of the services provided by

    .NET, including security and language

    interoperability. As you would expect from a

    language compiled into IL, C# is also strongly

    typed. Among other things, this means that

    data types are not always seamlesslyinterchangeable. Type Safety looks at

    conversions between primitive types.

  • 8/6/2019 Operators, Type Safety

    31/45

    Type Conversions

    Often, you need to convert data from one typeto another. Consider the following code:

    byte value1 = 10;

    byte value2 = 23;

    byte total;

    total = value1 + value2;

    Console.WriteLine(total);

    When you attempt to compile these lines, youget the following error message: Cannotimplicitly convert type int to byte'

  • 8/6/2019 Operators, Type Safety

    32/45

    The problem here is that when you add 2 bytes

    together, the result will be returned as an int ,

    not as another byte . This is because a byte can

    contain only 8 bits of data, so adding 2 bytes

    together could very easily result in a value that

    cannot be stored in a single byte . If you dowant to store this result in a byte variable, you

    are going to have to convert it back to a byte .

    The following sections discuss two conversionmechanisms supported by C# implicit and

    explicit.

  • 8/6/2019 Operators, Type Safety

    33/45

    Implicit Conversions Conversion between types can normally be

    achieved automatically (implicitly) only if youcan guarantee that the value is not changed inany way. This is why the previous code failed;by attempting a conversion from an int to abyte.

    byte value1 = 10;

    byte value2 = 23;

    long total; // this will compile fine

    total = value1 + value2;

    Console.WriteLine(total);

  • 8/6/2019 Operators, Type Safety

    34/45

    The following table shows the implicit typeconversions supported in C#:

    From To

    Sbyte- short, int, long, float, double,decimal

    byte - short, ushort, int, uint long,ulong,float, double,decimal

    Short- int, long, float, double, decimal

    Ushort- int, uint, long, ulong, float,double, decimal

    Int- long, float double, decimal

  • 8/6/2019 Operators, Type Safety

    35/45

    uint - long, ulong, float, double,

    decimal

    Long- ulong float, double, decimal

    float - double

    Char- ushort, int, uint, long, ulong,float, double, decimal,

  • 8/6/2019 Operators, Type Safety

    36/45

    Explicit Conversion

    Many conversions cannot be implicitly madebetween types, and the compiler will give youan error if any are attempted. These are someof the conversions that cannot be made

    implicitly: int to short Data loss is possible.

    int to uint Data loss is possible.

    uint to int Data loss is possible. float to int You will lose everything after

    the decimal point.

  • 8/6/2019 Operators, Type Safety

    37/45

    Any numeric type to char Data loss is

    possible.

    decimal to any numeric type The decimal

    type is internally structured differently from

    both integers and floating-point numbers.

    int? to int The nullable type may have the

    value null.

    However, you can explicitly carry out such

    conversions using casts.

  • 8/6/2019 Operators, Type Safety

    38/45

    A cast looks like this:

    long val = 30000;int i = (int)val; // A valid cast.

    You indicate the type to which you are casting

    by placing its name in parentheses before the

    value to be converted.

    Casting can be a dangerous operation to

    undertake. Even a simple cast from a long to

    an int can cause problems if the value of the

    original long is greater than the maximum

    value of an int:

  • 8/6/2019 Operators, Type Safety

    39/45

    Using casts, you can convert most primitivedata types from one type to another; for

    example. double price = 25.30;

    int P = (int)(price + 0.5);

    Output will be 25.

    In another code:

    ushort c = 43;

    char symbol = (char)c; Console.WriteLine(symbol);

    Output will be +.

  • 8/6/2019 Operators, Type Safety

    40/45

    long val = 3000000000;

    int i = (int)val; // An invalid cast. Themaximum int is 2147483647

    No error will be generated but gives

    unpredictable output.

    Another alternative is :

    long val = 3000000000;

    int i = checked((int)val);

  • 8/6/2019 Operators, Type Safety

    41/45

    You can convert an array element of type double

    to a struct member variable of type int.

    struct ItemDetails

    {

    public string Description;

    public int ApproxPrice;

    }

    double[] Prices = { 25.30, 26.20, 27.40, 30.00 };

    ItemDetails id;

    id.Description = Hello there.;

    id.ApproxPrice = (int)(Prices[0] + 0.5);

  • 8/6/2019 Operators, Type Safety

    42/45

  • 8/6/2019 Operators, Type Safety

    43/45

    int? a = null;

    int b = (int)a; // Will throw exception

    If you need to convert between numeric andstring, you can use methods provided in the.NET class library.The Object class

    implements a ToString() method: int i = 10;

    string s = i.ToString();

    Similarly, if you need to parse a string toretrieve a numeric or Boolean value, you canuse the Parse() method.

  • 8/6/2019 Operators, Type Safety

    44/45

    This method is supported by all the predefined

    value types:

    string s = 100;

    int i = int.Parse(s);

    Console.WriteLine(i + 50); Note that Parse() will register an error by

    throwing an exception if it is unable to convert

    the string.

  • 8/6/2019 Operators, Type Safety

    45/45

    ThankYou !