Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can do it, but not in a generic type. Generic type inference like this only occurs for generic methods. Declare a separate <em>non</em>-generic type, with a generic method:</p> <pre><code>public class XYZ { public static XYZ Action&lt;T, TKey&gt; (TKey key, T element) { return new XYZ&lt;T&gt;(element); } } </code></pre> <p>EDIT: Responding to the question edit.</p> <p>No, you can't do something like this:</p> <pre><code>abc.Accept(Ordering.By(u =&gt; u.Id)); </code></pre> <p>The problem is the inner expression:</p> <pre><code>Ordering.By(u =&gt; u.Id) </code></pre> <p>What's the type of <code>u</code> here? It could be any class with an <code>Id</code> property. Note that the C# compiler will need to work out the type of this expression <em>before</em> it looks at <code>abc.Accept</code>. Even if <code>abc.Accept</code> <em>only</em> worked for an <code>Ordering&lt;User&gt;</code>, it would fail.</p> <p>There are three options here:</p> <ul> <li><p>Use a static method in the generic class, specifying the source type argument explicitly, and inferring the key type argument:</p> <pre><code>Ordering&lt;User&gt;.By(u =&gt; u.Id) </code></pre></li> <li><p>Use a generic method in a non-generic class, specifying both type arguments explicitly:</p> <pre><code>Ordering.By&lt;User, string&gt;(u =&gt; u.Id) </code></pre></li> <li><p>Use a generic method in a non-generic class, specifying the type of the lambda parameter explicitly, and letting the compiler infer the key type argument:</p> <pre><code>Ordering.By((User u) =&gt; u.Id) </code></pre></li> </ul> <p>Obviously, all of these cases require you to specify the type explicitly somewhere.</p> <p>One other option which is a <em>little</em> bit weird is relevant if you've typically already got an instance of <code>User</code> (or at least a variable of that type). You can use that as a sort of example, which gets ignored:</p> <pre><code>public static Ordering&lt;T&gt; By&lt;T,TKey&gt;(Expression&lt;Func&lt;T, TKey&gt;&gt; func, T example) { return By&lt;T, TKey&gt;(func); } ... Ordering.By(u =&gt; u.Id, dummyUser); </code></pre>
 

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