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?
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.
4) Enum constants are implicitly static and final and can not be changed once created.
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.
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
{ }
How about parsing the Color property to your enum first
if ((ColorEnum) Enum.Parse(typeof (ColorEnum), thatObject.Color.ToString()) == ColorEnum.Red)
{
// do something
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With