-1

We have a class that for containing filter criteria used in searches. In the class is a dictionary of filter criteria which contains a value.

What I want to do is something like this.

protected string GetSearchValue(string name)
{
    if (!FilterCache.HasFilter(name)) return string.Empty;

    var filterType = FilterCache.GetFilterType(name);

    var filter = FilterCache.GetFilter<filterType>(name); // <- This fails

    if (filter == null || !filter.IsSet) return string.Empty;

    return filter.Value.ToString();         
}

GetFilterType looks like this:

    public Type GetFilterType(string name)
    {
        return SearchElements[name].GetType();
    }

In the end, I want to get the value of filter and return it to the UI.

amber
  • 1,067
  • 3
  • 22
  • 42
  • Could you show us the definition of `SearchElements` and explain more what you want the type of `filter` to be? – JaredPar Dec 13 '11 at 16:41
  • 1
    Possible duplicate of http://stackoverflow.com/questions/513952/c-sharp-specifying-generic-collection-type-param-at-runtime. – Roy Dictus Dec 13 '11 at 16:42
  • possible duplicate of [How to use reflection to call generic Method?](http://stackoverflow.com/questions/232535/how-to-use-reflection-to-call-generic-method) – nawfal Jan 17 '14 at 14:01

1 Answers1

0

You need to use reflection to call a generic with the type parameter not known at compile time, like this:

var getFilterGeneric = typeof(FilterCache)
    .GetMethod("GetFilter")
    .MakeGenericMethod(filterType)
    .Invoke(typeof(FilterCache) /* or null */, name);
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523