Note that there are some explanatory texts on larger screens.

plurals
  1. POGeneric extension methods in C#: what will happen in this edge case?
    primarykey
    data
    text
    <p>In a recent <a href="https://stackoverflow.com/questions/3255450/anti-constraint-on-c-generics">question of mine</a> I learned that if there are more than one extension methods with constraints that match the given type, the most specific one will be chosen. This got me thinking - how does the compiler determine which one is "more specific"? And what will the outcome be?</p> <p>Let's say I have the following classes:</p> <pre><code>public MyClass : IComparable, IDisposable { // Implementation of members } public static class MyExtensions { public static void DoSomething&lt;T&gt;(this T item) where T : IComparable { /* whatever */ } public static void DoSomething&lt;T&gt;(this T item) where T : IDisposable { /* whatever else */ } } </code></pre> <p>If I now use the extension method as </p> <pre><code>var instance = new MyClass(); instance.DoSomething(); </code></pre> <p>which method will be used? Or will the compiler throw an error?</p> <p>Note: I'm not saying this is good design, or even that I have a case where I need to do this. But the term "more specific" was loose enough to make me ponder this, and now I have to know! :P</p> <p><strong>Update:</strong> I guess I wasn't really as interested in <em>what</em> will happen in the above example, as in <em>why</em>. It came to my mind since I'd been doing stuff like</p> <pre><code>public static class CollectionExtensions { public static void DoSomething&lt;T&gt;(this T items) where T : IList { ... } public static void DoSomething&lt;T&gt;(this T items) where T : IEnumerable { ... } } </code></pre> <p>where the compiler knows to choose the first method for <code>new List&lt;Something&gt;().DoSomething()</code>, since it is "closer" to the type passed. What I was interested in then, was "what does <em>closer</em> in this context mean? How will the compiler react if the constraints are from two different inheritance chains? Why?"</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.
 

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