1

I have a EnumSearchExpressionProvider<TEnum> class. I need to assign an instance of this class inside attribute called SearchableEnumAttribute.

Here is my EnumSearchExpressionProvider<TEnum>,

public class EnumSearchExpressionProvider<TEnum> : StringSearchExpressionProvider where TEnum : struct
{
    public override ConstantExpression GetValue(string input)
    {
        if (!Enum.TryParse<TEnum>(input.Trim().Replace(" ", string.Empty), true, out var value))
        {
            throw new ArgumentException("Invalid search value.");
        }

        return Expression.Constant(value);
    }
}

Here is my SearchableEnumAttribute class,

[AttributeUsage(AttributeTargets.Property)]
public class SearchableEnumAttribute : SearchableAttribute
{
    public SearchableEnumAttribute(Type enumType)
    {
        ExpressionProvider = new EnumSearchExpressionProvider<enumType>();
    }
}

In my model, I'm using this attribute to one of the property as,

[SearchableEnum(typeof(Position))]
public string Position { get; set; }

here is my Position Enum,

public enum Position
{
    [Display(Name = "Accountant")]
    Accountant,
    [Display(Name = "Chief Executive Officer (CEO)")]
    ChiefExecutiveOfficer,
}

However I'm getting compile error in this line in my SearchableEnumAttribute constructor,

ExpressionProvider = new EnumSearchExpressionProvider<enumType>();

How to convert Type to TEnum? Am I doing something impossible or wrong? Is there any better way to do this? Please assist me.

fingers10
  • 6,675
  • 10
  • 49
  • 87

1 Answers1

4

something like:

ExpressionProvider = (StringSearchExpressionProvider)Activator.CreateInstance(
    typeof(EnumSearchExpressionProvider<>).MakeGenericType(enumType));

?

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • 1
    Should be noted that this is not suited for "heavy usage" as `Activator.CreateInstance` takes "ages" compared with some other possibilities https://stackoverflow.com/questions/6582259/fast-creation-of-objects-instead-of-activator-createinstancetype/6882881 (and that rather then using this, the API may should be improved) – X39 Oct 17 '19 at 10:05
  • @X39 So is it possible to make this better? – fingers10 Oct 17 '19 at 10:09
  • 2
    @fingers10 the usual trick is to cache your strategy per type, so that you don't need to keep doing it – Marc Gravell Oct 17 '19 at 10:15