Note that there are some explanatory texts on larger screens.

plurals
  1. POWhen do Extension Methods break?
    text
    copied!<p>We are currently discussing whether Extension methods in .NET are bad or not. Or under what circumstances Extension methods can introduce hard to find bugs or in any other way behave unexpectedly.</p> <p>We came up with:</p> <ul> <li>Writing an extension method for types that are not under your control (e.g. extending DirectoryInfo with GetTotalSize(), etc...) is bad, because the owner of the API could introduce a method that hides our extension - and might have different edge cases. For example testing for null in an extension method will automatically translate into a NullReferenceException if the extension method is no longer used due to hiding.</li> </ul> <p>Question:</p> <ul> <li>Are there any other dangerous situations than "hiding" that we are not thinking of?</li> </ul> <p>Edit:</p> <p>Another very dangerous situation. Suppose you have an extension method:</p> <pre><code>namespace Example.ExtensionMethods { public static class Extension { public static int Conflict(this TestMe obj) { return -1; } } } </code></pre> <p>And use it:</p> <pre><code>namespace Example.ExtensionMethods.Conflict.Test { [TestFixture] public class ConflictExtensionTest { [Test] public void ConflictTest() { TestMe me = new TestMe(); int result = me.Conflict(); Assert.That(result, Is.EqualTo(-1)); } } } </code></pre> <p>Notice that the namespace where you use it is longer.</p> <p>Now you reference a dll with this:</p> <pre><code>namespace Example.ExtensionMethods.Conflict { public static class ConflictExtension { public static int Conflict(this TestMe obj) { return 1; } } } </code></pre> <p>And your Test will fail! It will compile without a compiler error. It will <strong>simply fail</strong>. Without you even having to specify "using Example.ExtensionMethods.Conflict". The compiler will walk the namespace name and find Example.ExtensionMethods.Conflict.ConflictExtension before Example.ExtensionMethods.Extension and will use that <strong>without ever complaining about ambiguous extension methods</strong>. Oh the horror!</p>
 

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