Sivas <si***@webtraveller.com.au> wrote:
Can anyone tell me why this does not work:
---------------------------------------------
float b = 2.51F;
switch(b)
{
case 2.51F:
Console.WriteLine("A");
break;
default:
break;
}
Error: A value of an integral type expected
---------------------------------------------
It fails on the switch statement and does not go any further.
From the ECMA spec, section 15.7.2:
<quote>
The governing type of a switch statement is established by the switch
expression. If the type of the switch expression is sbyte, byte, short,
ushort, int, uint, long, ulong, char, string, or an enum-type, then
that is the governing type of the switch statement. Otherwise, exactly
one user-defined implicit conversion (§13.4) must exist from the type
of the switch expression to one of the following possible governing
types: sbyte, byte, short, ushort, int, uint, long, ulong, char,
string. If no such implicit conversion exists, or if more than one such
implicit conversion exists, a compile-time error occurs.
</quote>
Using floating point numbers in a switch statement would just be asking
for trouble, even if you could do it, due to the nature of floating
point and the dangers of equality comparisons.
--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too