Casting question


C

Constantine Filin

Greetings -

I have a very simple program:

=====================================
using System;

class Class1
{
static void Main(string[] args)
{
object o = 0; // o is now System.Int32 type
try
{
uint n = (uint)o; // generates invalid cast exception
}
catch( Exception e )
{
System.Console.Out.WriteLine(e);
}
}
}
=====================================

Running it generates an invalid cast exception on line
uint n = (uint)o;

Does anybody have an idea why casting an int to uint generates
an exception?

Thanks

Constantine
 
Ad

Advertisements

J

Jon Skeet [C# MVP]

Constantine Filin said:
Greetings -

I have a very simple program:

=====================================
using System;

class Class1
{
static void Main(string[] args)
{
object o = 0; // o is now System.Int32 type
try
{
uint n = (uint)o; // generates invalid cast exception
}
catch( Exception e )
{
System.Console.Out.WriteLine(e);
}
}
}
=====================================

Running it generates an invalid cast exception on line
uint n = (uint)o;

Does anybody have an idea why casting an int to uint generates
an exception?

Yes - because you're not casting from an Int32 to a UInt32. You're
casting from a *boxed* Int32 to a UInt32, which you can't do - when you
unbox, you need to do it to precisely the correct type. You can do:

uint n = (uint)(int)o;

though.
 
Ad

Advertisements

M

Mark Johnson

uint n = (uint)(int)o;

Well, that is interesting to know. Thank you!

Mark Johnson, Berlin Germany
(e-mail address removed)

Jon Skeet said:
Constantine Filin said:
Greetings -

I have a very simple program:

=====================================
using System;

class Class1
{
static void Main(string[] args)
{
object o = 0; // o is now System.Int32 type
try
{
uint n = (uint)o; // generates invalid cast exception
}
catch( Exception e )
{
System.Console.Out.WriteLine(e);
}
}
}
=====================================

Running it generates an invalid cast exception on line
uint n = (uint)o;

Does anybody have an idea why casting an int to uint generates
an exception?

Yes - because you're not casting from an Int32 to a UInt32. You're
casting from a *boxed* Int32 to a UInt32, which you can't do - when you
unbox, you need to do it to precisely the correct type. You can do:

uint n = (uint)(int)o;

though.
 

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