Unboxing simple types

M

muriwai

Hi,

I use C# 2.0 with the following:

object obj = ( int ) 1;

func( obj ); // Unboxing int to uint

void func( object obj )
{
#if true
uint v = ( uint ) obj; // Throws an invalid cast exception
#else
if( obj.GetType() == typeof( int ) ) // UGLY
{
uint v = ( uint )( int ) obj;
}
else
{
uint v = ( uint ) obj;
}
#endif
}

So I have the method which receives boxed numeric positive values, both
signed and unsigned. The method knows that the parameter is a numeric value
which should be convertible to uint. Is there an elegant method of casting
the parameter to uint without having to check the type of the parameter
first?

Thanks
 
J

Jon Skeet [C# MVP]

So I have the method which receives boxed numeric positive values, both
signed and unsigned. The method knows that the parameter is a numeric value
which should be convertible to uint. Is there an elegant method of casting
the parameter to uint without having to check the type of the parameter
first?

Convert.ToUInt32() perhaps?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top