user11563063
user11563063

Reputation:

Why does int.Parse not work on an Enum value?

can you tell me how this first line converts to int and second doesn't work?

public enum SomeEnumerator { AndHisValue, second, third }

int a = (int)(SomeEnumerator.AndHisValue);

int a = int.Parse(SomeEnumerator.AndHisValue);

Type of AndHisValue is string.

Image

Upvotes: 0

Views: 87

Answers (1)

user1781290
user1781290

Reputation: 2874

As you show in your image, SomeEnumerator is not of type string, but instead an enum.

string constants are denoted by " around them. enum constants, such as SomeEnumerator.AndHisValue are their own kind of value, each usually having their own distinct value.

You are allowed to directly cast any enum-value to int or string, but as int.Parse() expects a string you cannot use your enumerator value here

(see https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/enum as reference for enums)

Upvotes: 1

Related Questions