Reputation: 7325
I'm using reflection to retrieve the value of a property from an object. The value is an enum:
enum MyEnum
{
None,
SomeValue
}
Which is on an object, and the property also has an attribute
class MyObject
{
[MyAttribute(ExclusionValue = MyEnum.None)]
public MyEnum EnumProperty { get; set; }
}
So when I get to the reflection part of things I would like to check if the value is equal to the ExclusionValue
// exclusionValue is the value taken from the attribute
// propertyValue is the value retrieved by reflection of the containing object, so at
// this time it just an `object` type.
if(exclusionValue == propertyValue)
{
// Both values are `MyEnum.None` but the if statement never evaluates true.
}
I've tried to cast the exclusionValue
to an object so that they are both the same visible type
if((object)exclusionValue == propertyValue)
But this never returns true either. They are definitely the same enum value. Also, I can't explicitly cast anything in this if
statement because there are many other properties in the object of all different types (not just enums) that need this same check, for example:
class MyObject
{
[MyAttribute(ExclusionValue = MyEnum.None)]
public MyEnum EnumProperty { get; set; }
[MyAttribute(ExclusionValue = false)]
public bool BoolProperty { get; set; }
}
Edit
They will only ever be value types (no structs) or strings.
Upvotes: 1
Views: 94
Reputation: 103585
You need to unbox the object you got via reflection to a MyEnum
.
Currently you are comparing objects for equality, which tests for reference equality. They are not the same object, so it returns false.
This should behave as you expect:
if (exclusionValue == (MyEnum)propertyValue)
Or, you can call the Equals
method instead:
if (exclusionValue.Equals(propertyValue))
Which will call the Enum.Equals
method, which will do the right thing.
Upvotes: 1