Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat is the appropriate way to strongly type the return of a generic function?
    primarykey
    data
    text
    <p>I'm writing a filter function to return the specific type specified out of a larger collection of supertypes (objects for example). The idea is I give you an enumerable and you return me all the strings for example. you can write it this way without generics:</p> <pre><code>public static IEnumerable Filter(IEnumerable source, Type type) { List&lt;object&gt; results = new List&lt;object&gt;(); foreach(object o in source) { if(o != null &amp;&amp; o.GetType() == type) { results.Add(o); } } return results; } </code></pre> <p>if we want to return generics there are a few different ways to go about it.</p> <p>As a straight port:</p> <pre><code>public static IEnumerable&lt;TResult&gt; Filter&lt;TResult&gt; (IEnumerable source, Type type) </code></pre> <p>Pass in an 'example':</p> <pre><code>IEnumerable&lt;TResult&gt; Filter&lt;TResult&gt; (IEnumerable source, TResult resultType) </code></pre> <p>Ultimately what I think is cleanest:</p> <pre><code>public static IEnumerable&lt;T&gt; Filter&lt;T&gt;(IEnumerable source) </code></pre> <p>The second type would be called entirely with parameters (and infer the type):</p> <pre><code>Filter(myList, "exampleString"); </code></pre> <p>where as the final version there would get called with a type specifier:</p> <pre><code>Filter&lt;string&gt;(myList); </code></pre> <p>What is the appropriate way to strongly type the return of a generic function, where the return type isn't automatically implied in the signature? (why?)</p> <p>(Edit Note: Our input is NOT typed, e.g. IEnumerable&lt;T&gt;. At best it would be IEnumerable. This function is returning the Ts out of the whole collection of other types.)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload