'How to get toString method for the Nullable Enum for building an Expression Call
enum StrategyType
{
Straddle,
Butterfly
}
class Test
{
public StrategyType strategy {get; set;}
}
bool IsNullableEnum(Type t)
{
Type u = Nullable.GetUnderlyingType(t);
return (u != null) && u.IsEnum;
}
var toStringMethod = typeof(Enum).GetMethod("ToString", new Type[] { });
var entity = new Test();
var entityParameter = Expression.Parameter(entity);
Expression memberProperty = Expression.Property(entityParameter, "strategy");
memberProperty = Expression.Call(memberProperty, toStringMethod);
If I change the StrategyType Enum in the Test class to Nullable like below:
StrategyType? strategyType {get; set;}
Then, I am unable to find out the way to get the toString method for Nullable Enum, similar to the one I have done for simple Enum StrategyType.
Can anyone please help.
Solution 1:[1]
Nullable<> is a little tricky. When you find such a property you have to check against the given entity what you get back from prop.GetValue(entity). Either this is null (and trying to call ToString() would be impossible) or you get back the value type (but boxed as an object), but you can call the normal ToString() method.
if (IsNullableEnum(prop.PropertyType) && prop.GetValue(entity) != null)
memberProperty = Expression.Call(memberProperty, toStringMethod);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Oliver |
