Generic unboxing of boxed value types
Posted
by slurmomatic
on Stack Overflow
See other posts from Stack Overflow
or by slurmomatic
Published on 2010-05-03T16:45:06Z
Indexed on
2010/05/03
16:48 UTC
Read the original article
Hit count: 291
I have a generic function that is constrained to struct. My inputs are boxed ("objects"). Is it possible to unbox the value at runtime to avoid having to check for each possible type and do the casts manually?
See the above example:
public struct MyStruct
{
public int Value;
}
public void Foo<T>(T test)
where T : struct
{
// do stuff
}
public void TestFunc()
{
object o = new MyStruct() { Value = 100 }; // o is always a value type
Foo(o);
}
In the example, I know that o must be a struct (however, it does not need to be MyStruct ...). Is there a way to call Foo without tons of boilerplate code to check for every possible struct type?
Thank you.
© Stack Overflow or respective owner