How to unbox from object to type it contains, not knowing that type at compile time?

Paul Kyrejto picture Paul Kyrejto · Mar 22, 2013 · Viewed 13.5k times · Source

At the run-time I get boxed instance of some type. How to unbox it to underlying type?

Object obj;
String variable = "Some text";

obj = variable // boxing;

// explicit unboxing, because we know the type of variable at compile time.

var x = (String)obj     

// Now let's pretend that we don't know the type of underlying object at compile time. 

Type desiredType = obj.GetType(); // But we can figure out.

//And now the question. 
//How to express something like this:

var y = (desiredType)obj; //Need to get unboxed instance of initial variable here; 

Answer

Marc Gravell picture Marc Gravell · Mar 22, 2013

If you don't know the type at compile time, then you can't unbox because you have nowhere to put it - all you can do is store it in an object, which is: boxed.

The same also applies to reference-types like string: you can't cast it to the right type if you don't know the type at compile time: you have nowhere to put it.

You can special-case a few types, for example:

if(obj is int) {
    int i = (int)obj;
    ...
} ...

Another trick that is sometimes (not often) helpful is to switch into generics; then instead of talking in terms of object you are talking in terms of T. This has... limited use though. The easiest way to do that is via dynamic, for example:

dynamic obj = ...
Foo(obj);
...
Foo<T>(T val) { ... code with T ... }

you can also add special cases to that appreach:

Foo(string val) { ... code with string ...}
Foo(int val) { ... code with int ...}

However, frankly I suggest it may be better to look hard at what you are trying to do.