Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic method to replace two

Tags:

c#

generics

I would like to make below methods generic, this method makes a search using a search service, and all possible URL's are in a dictionary.

public XDocument DoSearchForTypeA()
{
    return searchService.Search(dictionary["optiona"]);
}

public XDocument DoSearchForTypeB()
{
    return searchService.Search(dictionary["optionb"]);
}

I was thinking on doing something like this:

public XDocument DoSearch<T>()
{
    if(typeof(T)==typeof(MyTypeA))
    {
        return searchService.Search(dictionary["optiona"]);
    }
    return searchService.Search(dictionary["optionb"]);
}

I see my solution really awful. Mainly cause i dont like the switches or ifs parsing each type. It makes the code not so flexible for scale it.

I would like to have a more elegant solution, but I have the feeling that this is not the best example for using generic methods. Could you give me some advices on this reflection?

like image 510
Josema Avatar asked Nov 19 '25 22:11

Josema


1 Answers

Dictionary is one of the options:

private static Dictionary<Type, String> s_Search = new Dictionary<Type, String>()
{
    {typeof(MyTypeA), "optiona"},
    {typeof(MyTypeB), "optionb"}
}

...

public XDocument DoSearch<T>()
{ 
    return searchService.Search(dictionary[s_Search(typeof(T))]);
}
like image 154
Dmitry Bychenko Avatar answered Nov 22 '25 12:11

Dmitry Bychenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!