Unboxing to unknown type

Posted by Robert on Stack Overflow See other posts from Stack Overflow or by Robert
Published on 2010-05-19T20:15:56Z Indexed on 2010/05/19 20:20 UTC
Read the original article Hit count: 292

Filed under:
|

I'm trying to figure out syntax that supports unboxing an integral type (short/int/long) to its intrinsic type, when the type itself is unknown.

Here is a completely contrived example that demonstrates the concept:

// Just a simple container that returns values as objects struct DataStruct { public short ShortVale; public int IntValue; public long LongValue; public object GetBoxedShortValue() { return LongValue; } public object GetBoxedIntValue() { return LongValue; } public object GetBoxedLongValue() { return LongValue; } }

static void Main( string[] args ) {

DataStruct data;

// Initialize data - any value will do data.LongValue = data.IntValue = data.ShortVale = 42;

DataStruct newData;

// This works if you know the type you are expecting! newData.ShortVale = (short)data.GetBoxedShortValue(); newData.IntValue = (int)data.GetBoxedIntValue(); newData.LongValue = (long)data.GetBoxedLongValue();

// But what about when you don't know? newData.ShortVale = data.GetBoxedShortValue(); // error newData.IntValue = data.GetBoxedIntValue(); // error newData.LongValue = data.GetBoxedLongValue(); // error }

In each case, the integral types are consistent, so there should be some form of syntax that says "the object contains a simple type of X, return that as X (even though I don't know what X is)". Because the objects ultimately come from the same source, there really can't be a mismatch (short != long).

I apologize for the contrived example, it seemed like the best way to demonstrate the syntax.

Thanks.

© Stack Overflow or respective owner

Related posts about c#

Related posts about inferred-type