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
As you note, the range of
Int32is -2,147,483,648 to 2,147,483,647, so any number within that range can be held, but ONLY numbers within that range can be held. 4,294,901,760 is greater than 2,147,483,647, so doesn’t fit in anInt32.What to do about this depends on what you want to achieve. If you just want an
Int32with the bit patternffff0000, then as suggested useunchecked:ynow has the value -65536, which is that bit pattern interpreted as a signed integer.However! If you actually want the value 4,294,901,760 you should use a datatype appropriate to it – so
UInt32.