Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check enum property when the property is obtained from dynamic in C#?

Suppose I know that property Color of an object returns an enumeration that looks like this one:

enum ColorEnum {
   Red,
   Green,
   Blue
};

and I want to check that a specific object of unknown type (that I know has Color property) has Color set to Red. This is what I would do if I knew the object type:

ObjectType thatObject = obtainThatObject();
if( thatObject.Color == ColorEnum.Red ) {
   //blah
}

The problem is I don't have a reference to the assembly with ColorEnum and don't know the object type.

So instead I have the following setup:

dynamic thatObject = obtainThatObject();

and I cannot cast because I don't know the object type (and the enum type). How should I check the Color?

if( thatObject.Color.ToString() == "Red" ) {
    //blah
}

does work but it looks like the worst examples of cargo cult code I've seen in "The Daily WTF".

How do I do the check properly?

like image 915
sharptooth Avatar asked Mar 04 '15 11:03

sharptooth


People also ask

How do you check if a property is an enum?

In C#, we can check the specific type is enum or not by using the IsEnum property of the Type class. It will return true if the type is enum. Otherwise, this property will return false. It is a read-only property.

Can enum values be changed?

4) Enum constants are implicitly static and final and can not be changed once created.

Can you change the value of an enum in C#?

You can't do this, it is a strongly-typed value, if you like. The elements of the enum are read-only and changing them at runtime is not possible, nor would it be desirable.


2 Answers

In the side assembly:

enum ColorEnum
{
    Red,
    Green,
    Blue
};

We know that Red exists, but nothing about other colors. So we redefine the enum in our assembly with known values only.

enum KnownColorEnum // in your assembly
{
    Red
};

Therefore we can perform parsing:

public static KnownColorEnum? GetKnownColor(object value)
{
    KnownColorEnum color;

    if (value != null && Enum.TryParse<KnownColorEnum>(value.ToString(), out color))
    { return color; }

    return null;
}

Examples:

// thatObject.Color == ColorEnum.Red
// or
// thatObject.Color == "Red"
if (GetKnowColor(thatObject.Color) == KnownColorEnum.Red) // true
{ }

// thatObject.Color == ColorEnum.Blue
if (GetKnowColor(thatObject.Color) == KnownColorEnum.Red) // false
{ }
like image 87
Yoh Deadfall Avatar answered Sep 24 '22 00:09

Yoh Deadfall


How about parsing the Color property to your enum first

if ((ColorEnum) Enum.Parse(typeof (ColorEnum), thatObject.Color.ToString()) == ColorEnum.Red)
{
    // do something
}
like image 43
Szeki Avatar answered Sep 21 '22 00:09

Szeki