0

I have following generic class:

public class SearchModel<T>
{
    public string Name { get; set; }
    public int? UserId { get; set; }

    public List<T> result { get; set; }
}

public class A{
    ..
    ..
}

public class B{
    ..
    ..
}

and List in SearchModel class can be of type A/B. Now I have these two function calls which gives me appropriate results.

public List<A> SearchApplicationsForA(SearchModel<A> model){
}

public List<B> SearchApplicationsForB(SearchModel<B> model){
}

I was wondering if I can write a generic function which can identify the type of T and calls respective functions. For eg.

    public List<T> SearchApplications<T>(SearchModel<T> model)
    {
        if (typeof(T) == typeof(A))
        {
            return SearchVerificationsForA(model);
        }
        else if (typeof(T) == typeof(B))
        {
            return SearchApplicationsForB(model);
        }
    }

Is it possible to write such functions?

coder_kp
  • 1
  • 1

2 Answers2

0

Could you not

public List<A> SearchApplications(SearchModel<A> model) {
    return SearchVerificationsForA(model);
}

public List<B> SearchApplications(SearchModel<B> model) {
    return SearchVerificationsForB(model);
}

and not even bother with testing the type?

xori
  • 716
  • 7
  • 9
  • This would unquestionably work, except it is using function overloading, not a generic object. It is quite possibly the direction the OP *should* go; but doesn't really answer the question stated. – BradleyDotNET Oct 06 '14 at 19:39
  • yes I agree, this is more a possible option. – xori Oct 06 '14 at 19:41
  • I already have two separate functions calls for methods mentioned above but was checking if there is a better way to code this. – coder_kp Oct 06 '14 at 19:49
  • @coder_kp but notice that both of my functions are named the same thing? http://csharp.net-tutorials.com/classes/method-overloading/ *Edit* wrong link – xori Oct 06 '14 at 19:52
0

You should consider this syntax instead:

public List<T> SearchApplications<T>(SearchModel<T> model)
{
    if (model is A)
    {
        return SearchVerificationsForA(model);
    }
    else if (model is B)
    {
        return SearchApplicationsForB(model);
    }
}
Glenn Ferrie
  • 10,290
  • 3
  • 42
  • 73
  • I tried this way but those two functions calls are failing to compile because of invalid arguments. This may be because the expected parameter is a template parameter for both. – coder_kp Oct 06 '14 at 19:47