[Mono-list] Enum problem
Iain McCoy
iain@mccoy.id.au
Sat, 16 Oct 2004 21:33:57 +1000
On Sat, 2004-10-16 at 13:17 +0200, Francis Brosnan Blázquez wrote:
> Hi.
>
> Working with enumerations I've found an strange behaviour. If you
> compile the following source code and run it:
>
> --
> using System;
>
> public class EnumTest {
>
> public enum TipoCarga {
> Positivo = 1/3,
> Negativo = 1 + (1/3),
> Neutro = 1,
> }
>
> public static void Main () {
> TipoCarga carga;
>
> carga = TipoCarga.Positivo;
> Console.WriteLine ("carga value is: {0}", carga);
>
> carga = TipoCarga.Neutro;
> Console.WriteLine ("carga value is: {0}", carga);
>
> carga = TipoCarga.Negativo;
> Console.WriteLine ("carga value is: {0}", carga);
> }
> }
> --
>
>
> You get the following output:
> carga value is: Positivo
> carga value is: Neutro
> carga value is: Neutro
>
> That is, on every assignment which uses TipoCarga.Negativo doesn't work.
> I've been reading about how enumerations works and seens to be that you
> can only use values from byte, sbyte, short, ushort, int, uint, long, or
> ulong types but not float or double types which can hold values as 1/3
> and 1 + (1/3).
>
> The odd thing is that assignment for Positivo = 1/3 works perfectly.
>
> Maybe mcs mustn't allow someone to compile the previous source code?
I haven't got a windows machine to run csc on to double check, but I
suspect what you're seeing is the compiler automatically coercing all of
your enum values to ints. This means that 1/3 = 0, so 1 + 1/3 = 0 and
therefore TipoCarga.Neutro == TipoCarga.Negativo. Whether this is what
css does or not I have no idea, but according to the spec it seems to be
correct (section 14.3 of the C# language specification 1.2):
"If the declaration of the enum member has a constant-expression
initializer, the value of that constant expression, implicitly converted
to the underlying type of the enum, is the associated value of the enum
member"
--
Iain McCoy <iain@mccoy.id.au>