NGWS SDK Documentation  

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Unboxing Conversion

Unboxing conversion 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. An unboxing operation consists of:

The following statements demonstrate both boxing and unboxing operations:

int i = 123;          // A value type
object box = i;       // Boxing
int j = (int)box;     // Unboxing

The following figure demonstrates the result of the preceding statements.

Unboxing Conversion

For an unboxing conversion to a given value type to succeed at run time, the value of the source argument must be a reference to an object that was previously created by boxing a value of that value type. If the source argument is null or a reference to an incompatible object, an InvalidCastException is thrown.

Example

The following example demonstrates a case of invalid unboxing. By using try and catch, an error message is displayed when the error occurs.

// Example to show how incorrect unboxing leads to InvalidCastException
using System;
public class UnboxingTest {
   public static void Main() {
      int intI = 123;
      //Boxing
      object o = intI;
      // Reference to incompatible object produces InvalidCastException
      try {
         int intJ = (short) o;
         Console.WriteLine("Unboxing OK.");
      }
      catch (InvalidCastException e) {
         Console.WriteLine("Error: Incorrect unboxing.");
      }
   }
}

Output

Error: Incorrect unboxing.

If you change the statement

int intJ = (short) o;

to:

int intJ = (int) o;

the conversion will be performed, and you will get the output Unboxing OK.

See Also

Boxing and Unboxing | Boxing Conversion