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 ShortVale; }
public object GetBoxedIntValue() { return IntValue; }
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.
GetBoxed
methods are returningLongValue
. Typo? – Hefterdynamic
). If you do know the type after unboxing, then unbox to that type. In your example, you know that newData.IntValue can only be assigned with an int, so that you have to donewData.IntValue = (int)yourUnknownBoxedValue;
. If this then fails, you can't assign it to newData.IntValue. If it doesn't fail, then you're fine. So what I'm saying is really: you should think up a not-contrived example, because this makes no sense. – Isaacson