Page 166 - CSharp/C#
P. 166

Comparisons with boxed value types


        If value types are assigned to variables of type object they are boxed - the value is stored in an
        instance of a System.Object. This can lead to unintended consequences when comparing values
        with ==, e.g.:


         object left = (int)1;  // int in an object box
         object right = (int)1; // int in an object box

         var comparison1 = left == right;      // false


        This can be avoided by using the overloaded Equals method, which will give the expected result.


         var comparison2 = left.Equals(right); // true


        Alternatively, the same could be done by unboxing the left and right variables so that the int
        values are compared:


         var comparison3 = (int)left == (int)right; // true



        Conversion of boxed value types


        Boxed value types can only be unboxed into their original Type, even if a conversion of the two Type
        s is valid, e.g.:


         object boxedInt = (int)1; // int boxed in an object

         long unboxedInt1 = (long)boxedInt; // invalid cast

        This can be avoided by first unboxing into the original Type, e.g.:



         long unboxedInt2 = (long)(int)boxedInt; // valid

        Read Built-in Types online: https://riptutorial.com/csharp/topic/42/built-in-types






























        https://riptutorial.com/                                                                             112
   161   162   163   164   165   166   167   168   169   170   171