Suggestions on Working with this Inherited Generic Method
Posted
by blu
on Stack Overflow
See other posts from Stack Overflow
or by blu
Published on 2010-03-19T21:43:34Z
Indexed on
2010/03/19
21:51 UTC
Read the original article
Hit count: 146
We have inherited a project that is a wrapper around a section of the core business model.
There is one method that takes a generic, finds items matching that type from a member and then returns a list of that type.
public List<T> GetFoos<T>()
{
List<IFoo> matches = Foos.FindAll(
f => f.GetType() == typeof(T)
);
List<T> resultList = new List<T>();
foreach (var match in matches)
{
resultList.Add((T)obj);
}
}
Foos can hold the same object cast into various classes in inheritance hierarchy to aggregate totals differently for different UI presentations. There are 20+ different types of descendants that can be returned by GetFoos.
The existing code basically has a big switch statement copied and pasted throughout the code. The code in each section calls GetFoos with its corresponding type.
We are currently refactoring that into one consolidated area, but as we are doing that we are looking at other ways to work with this method.
One thought was to use reflection to pass in the type, and that worked great until we realized the Invoke returned an object, and that it needed to be cast somehow to the List <T>.
Another was to just use the switch statement until 4.0 and then use the dynamic language options.
We welcome any alternate thoughts on how we can work with this method. I have left the code pretty brief, but if you'd like to know any additional details please just ask.
© Stack Overflow or respective owner