one advantage of an extension methods is that the original class doesn’t have to be “partial;” it can even be sealed. You can also put extension methods on an interface or on an enum.
Extension methods were introduced to make LINQ possible: LINQ adds a large number of extension methods to classes that implement collection interfaces.
]]>I get the semantic differences like null checking, but there must be a more fundamental difference i’m missing…
]]>There are two current reasons why I love extension methods: 1) enabling of fluent interfaces built on top of a “normal” canonical API and 2) a “poor man’s” .NET version of monkey-patching from the Ruby world. So, for unit testing frameworks, instead of having code like “Assert.Equal(foo, bar);”, I could have “foo.ShouldEqual(bar);” instead due to an extension method on object.
]]>I’m with you. In my viewpoint, “sugar” is pretty important. Programmers spend a lot of our days doing little tasks again and again — out of the box APIs often mean that we need to use 5 lines of code to do one line worth of work the ‘obvious’ way, and that we need 15 to do it the correct way.
Extension methods are a great way to codify correct practices and put them on our fingertips — so it’s easier to do things right than to do things wrong.
]]>Extension methods: Good for sugar, bad for logic.
]]>