0

Why does the following return false? The value object is of type SomeEnum at runtime.

I'm converting both the object to same type, however I still receive it as false.

What am I doing wrong?

object value = SomeEnum.FirstValue;
object parameter = 0;
Console.Write(Enum.ToObject(value.GetType(), parameter ?? 0) == Enum.Parse(value.GetType(), value.ToString()));

The problem is I cannot directly acess the SomeEnum type and I receive everything as object.

1
  • See my answer and try the line of code I posted. Commented Mar 25, 2019 at 4:22

2 Answers 2

4

Because you are comparing object instances; not Enum Values.

You need to convert both to enum and then compare. Or use the Object.Equals method.

Because when you box them inside an object they become different instances.

Try this instead:

 Enum.ToObject(value.GetType(), parameter ?? 0).Equals(Enum.Parse(value.GetType(), value.ToString()))
Sign up to request clarification or add additional context in comments.

6 Comments

Great. Actually that's what I did and it worked before I found your answer :) Thanks anyway.
@ZammyPage if my answer works please mark as answered for any one else searching google.
You need to convert both to enum and then compare. I suppose that's what it does when I use Enum.ToObject and Enum.Parse. They should both convert them to enum value types?
@ZammyPage Enum.ToObject does the opposite it converts to an object. Enum.Parse also converts to an object. In order for Enum.Parse to work you need to cast the result to an enum like this (someenum)Enum.Parse(somestring)
Yeah, make sense. Thanks mate.
|
0

It's possible to assign different integers to Enum values, they are not necessarily zero indexed.

Enumeration types C#

enum Day { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday,
Saturday };

When you create a new Day object, it will have a default value of Day.Sunday (0) if you do not explicitly assign it a value.

When you do not specify values for the elements in the enumerator list, the values are automatically incremented by 1.

enum MachineState
{
    PowerOff = 0,
    Running = 5,
    Sleeping = 10,
    Hibernating = Sleeping + 5
}

You can assign any values to the elements in the enumerator list of an enumeration type, and you can also use computed values:

2 Comments

That is not the reason. He is comparing instances and not values. See my answer. Just try the code and see that both objects have the same enum value
@Darkonekt yes, you got my upvote. Seemed an odd way to go about comparing enum values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.