Is it possible to unbox an object to more than one value type?

I have read in CLR via C#:

Unboxing is really just the operation of obtaining a pointer to the raw value type (data fields) contained within an object.

which means that if more than one value type is contained within an object they can be unboxed using the below syntax:

int a= (int) o; //assigns a to 10
char b= (char) o; // assigns b to 'b'

How to implement such object which supports multiple unboxing?

Jon Skeet
people
quotationmark

A boxed value can only be the boxed form of a single type - if you call o.GetType() you'll find out what that is.

In general, you can only unbox to the exact same type, with a few wrinkles:

  • You can unbox an enum value to its underlying integral type, and vice versa
  • There's no such thing as a boxed nullable value type - boxing will result in either a boxed form of the non-nullable type, or a null reference. You can unbox to a nullable value type, and the result will either be a null value (if the original reference was a null reference) or a non-null value containing the unboxed non-nullable value, if you see what I mean.

So for example:

object o = 10;
FileMode mode = (FileMode) o; // Valid conversion to enum

int? n = (int?) o; // n has a value of 10
n = null;
o = n; // o's value is a null reference
n = (int?) o; // n's value is the null int? value

people

See more on this question at Stackoverflow