|
|
|
 |
Reply From: |
Moreus |
That’s how enums works 
Sorry, I should have explained myself more clearly! 
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