Confusion with ENUMs

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By emilianop

I’m defining an enum as:

enum myEnum{ a, b, c}

if I parsed its entries with:

for item in myEnum:
    print(item)

I’d expect to see 0 1 2 but instead I’m seeing a b c
In order to get the actual values I need to use myEnum.values()

Is this expected? I thought the default output from enums would be their values, not the keys?

1 Like
:bust_in_silhouette: Reply From: Moreus

That’s how enums works :slight_smile:

you can check this code in C# C# Online Compiler | .NET Fiddle Enums there works same way

Moreus | 2023-03-19 09:31

Sorry, I should have explained myself more clearly! :slight_smile:

Consider the following:

enum my_enum {a,b,c}

var list = {}
list[my_enum.a] = "first"
list[my_enum.b] = "second"
list[my_enum.c] = "third"

now, regardless of what the call to my_enum.a produced by default (values or keys), I’d expect it to be consistent, therefore if I initialise something with list[my_enum.a] = "first"
I would expect for the retrieving operations to be the same between:

print( list[my_enum.a] )

and

for e in my_enum:
    print( list[e] )

But the second call won’t work, unless I do:

for e in my_enum.values():
    print(list[e])

Which is where I see the inconsistency in logic.

I saw your example, but I think you’re not allowed to run foreach (var s in Season) in C#, right?
So not sure how the above would map in a different language like C#

emilianop | 2023-03-20 09:14

is will look like C# Online Compiler | .NET Fiddle

using System;
				
public class Program
{
	public static void Main()
	{
		
		foreach(var sesons in Enum.GetNames(typeof(Season)))
		Console.WriteLine(sesons);
				foreach(var sesons in Enum.GetValues(typeof(Season)))
		Console.WriteLine(sesons);
	}
}

enum Season
{
    Spring,
    Summer,
    Autumn,
    Winter
}

Output:

Spring
Summer
Autumn
Winter
Spring
Summer
Autumn
Winter

names and values give the same output but one is string and second is enum
C# Online Compiler | .NET Fiddle in this i cast enum to ‘int’ too. Names cannot be cast

Moreus | 2023-03-20 11:33

Yes totally, I’m with you on that.

I’m talking about the fact that in C# you must cast it everywhere, you cannot do:

list[Season.Spring] = "first";

// Compilation error (line 11, col 8): Cannot implicitly convert type 'Season' to 'int'. An explicit conversion exists (are you missing a cast?)

but in GD you can do:

list[my_enum.a] = "first"

which, I’m assuming, is implicitly casting my_enum.a to int.
What I find confusing is that this implicit cast doesn’t happen everywhere, therefore this:

for e in my_enum.values():
    print(list[e])

instead, will fail

emilianop | 2023-03-21 01:27