Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can take a look on the MSDN documentation about extension methods: <a href="http://msdn.microsoft.com/en-us/library/vstudio/bb383977.aspx" rel="nofollow">Extension Methods (C# Programming Guide)</a>. The interesting part is under <em>Binding Extension Methods at Compile Time</em>:</p> <blockquote> <p>... it first looks for a match in the type's instance methods. If no match is found, it will search for any extension methods that are defined for the type, and bind to the <strong>first extension method that it finds</strong>. </p> </blockquote> <p>So this is why you see this behavior. And I actually can buy it, just imagine that somebody can overwrite how your application works with just one method <code>public static T Id&lt;T&gt;(this T item, string id) where T : object</code>. And if you will not see any compiler errors, you will think that everything is correct, and maybe everything will work, except some rarely cases. How confusing it could be?</p> <p>And one more bad thing about your approach. If I will consume your API and will see that for Button I have two methods: one in <code>HtmlElementExtensions</code> and one in <code>ButtonBaseExtensions</code> what will stop me of doing this <code>HtmlElementExtensions.Id(button, "id")</code> instead of <code>ButtonExtensions.Id(button, "id")</code>?</p> <p>In your case I'd prefer combined approach:</p> <pre><code>public static T Id&lt;T&gt;(this T item, string id) where T : HtmlElement { if (item is ButtonBase) { return (T)Id((ButtonBase)item); } else if (item is HtmlElement) { return (T)Id((HtmlElement)item); } throw new NotSupportedException("Type " + item.GetType() + " is not supported by Id extension method"); } private static ButtonBase Id(ButtonBase item, string id) { return item; } private static HtmlElement Id(HtmlElement item, string id) { return item; } </code></pre>
    singulars
    1. This table or related slice is empty.
    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.
    1. VO
      singulars
      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