I am writing a filter function to return a specific type specified from a larger collection of supertypes (e.g. objects). The idea is that I give you an enumerated value and you return me all the strings, for example. you can write this without generics:
public static IEnumerable Filter(IEnumerable source, Type type)
{
List<object> results = new List<object>();
foreach(object o in source)
{
if(o != null && o.GetType() == type)
{
results.Add(o);
}
}
return results;
}
if we want to return generics, there are several different ways to do this.
As a direct port:
public static IEnumerable<TResult> Filter<TResult>
(IEnumerable source, Type type)
Go to the example:
IEnumerable<TResult> Filter<TResult>
(IEnumerable source, TResult resultType)
Ultimately, what I consider the cleanest:
public static IEnumerable<T> Filter<T>(IEnumerable source)
The second type will be called completely with parameters (and deduce the type):
Filter(myList, "exampleString");
where the final version will be called using a type specifier:
Filter<string>(myList);
What is a suitable way to forcefully return the return of a generic function where the return type is not automatically implied in the signature? (Why?)
( : , IEnumerable <T> . IEnumerable. Ts .)