Alex Rivera | Logout

C# - Constant value '4294901760' cannot be converted to a 'int'

Asked 2011-05-17T07:24:51.083
9

Greetings,

I can't believe I'm asking such a basic question, but it doesn't make sense so here it is :).

In C# on Windows Phone 7 / .net, I'm trying to define a constant in a class as follows:

// error CS0266: Cannot implicitly convert type 'uint' to 'int'. 
// An explicit conversion exists (are you missing a cast?)
public const int RED = 0xffff0000;

If I put an (int) cast around it like so, I get another error:

// error CS0221: Constant value '4294901760' cannot be converted to a 'int' 
// (use 'unchecked' syntax to override)        
public const int RED = (int)0xffff0000;

But I know that my int is 32-bit, hence has a range of -2,147,483,648 to 2,147,483,647, see http://msdn.microsoft.com/en-us/library/5kzh1b5w(v=vs.80).aspx

So what gives?

Thanks in advance!

swine

Edit
Report

1 Answer

2

Try using unchecked as suggested by the compiler message:

public const int RED = unchecked((int)0xffff0000);

This defines RED as -65536, which is 0xffff0000 interpreted as signed int.

answered 2011-05-17T07:28:25.403

Your Answer