<p>The new extensions in .Net 3.5 allow functionality to be split out from interfaces.</p>

<p>For instance in .Net 2.0</p>

<pre><code>public interface IHaveChildren {
    string ParentType { get; }
    int ParentId { get; }

    List&lt;IChild&gt; GetChildren()
}
</code></pre>

<p>Can (in 3.5) become:</p>

<pre><code>public interface IHaveChildren {
    string ParentType { get; }
    int ParentId { get; }
}

public static class HaveChildrenExtension {
    public static List&lt;IChild&gt; GetChildren( this IHaveChildren ) {
        //logic to get children by parent type and id
        //shared for all classes implementing IHaveChildren 
    }
}
</code></pre>

<p>This seems to me to be a better mechanism for many interfaces.  They no longer need an abstract base to share this code, and functionally the code works the same. This could make the code more maintainable and easier to test.</p>

<p>The only disadvantage being that an abstract bases implementation can be virtual, but can that be worked around (would an instance method hide an extension method with the same name? would it be confusing code to do so?)</p>

<p>Any other reasons not to regularly use this pattern?</p>

<hr>

<p>Clarification:</p>

<p>Yeah, I see the tendency with extension methods is to end up with them everywhere. I'd be particularly careful having any on .Net value types without a great deal of peer review (I think the only one we have on a string is a <code>.SplitToDictionary()</code> - similar to <code>.Split()</code> but taking a key-value delimiter too)</p>

<p>I think there's a whole best practice debate there ;-)</p>

<p>(Incidentally: DannySmurf, your PM sounds scary.)</p>

<p>I'm specifically asking here about using extension methods where previously we had interface methods.</p>

<hr>

<p>I'm trying to avoid lots of levels of abstract base classes - the classes implementing these models mostly already have base classes. I think this model could be more maintainable and less overly-coupled than adding further object hierarchies.</p>

<p>Is this what MS has done to IEnumerable and IQueryable for Linq?</p>

[{'answer_id': 8054, 'author': 'TheSmurf', 'author_id': 1975282, 'author_profile': 'https://Stackoverflow.com/users/1975282', 'pm_score': 0, 'selected': False, 'text': "<p>One problem I can see is that, in a large company, this pattern could allow the code to become difficult (if not impossible) for anyone to understand and use. If multiple developers are constantly adding their own methods to existing classes, separate from those classes (and, God help us all, to BCL classes even), I could see a code base spinning out of control rather quickly.</p>\n\n<p>Even at my own job, I could see this happening, with my PM's desire to add every bit of code that we work on to either the UI or the data access layer, I could totally see him insisting on 20 or 30 methods being added to System.String that are only tangentially-related to string handling.</p>\n"}, {'answer_id': 8091, 'author': 'Vaibhav', 'author_id': 380, 'author_profile': 'https://Stackoverflow.com/users/380', 'pm_score': 3, 'selected': False, 'text': '<p>I think the best thing that extension methods replace are all those utility classes that you find in every project.</p>\n\n<p>At least for now, I feel that any other use of Extension methods would cause confusion in the workplace.</p>\n\n<p>My two bits.</p>\n'}, {'answer_id': 8564, 'author': 'Jon Limjap', 'author_id': 372, 'author_profile': 'https://Stackoverflow.com/users/372', 'pm_score': 3, 'selected': False, 'text': "<p>Extension methods should be used as just that: extensions. Any crucial structure/design related code or non-trivial operation should be put in an object that is composed into/inherited from a class or interface. </p>\n\n<p>Once another object tries to use the extended one, they won't see the extensions and might have to reimplement/re-reference them again.</p>\n\n<p>The traditional wisdom is that Extension methods should only be used for:</p>\n\n<ul>\n<li>utility classes, as Vaibhav mentioned</li>\n<li>extending sealed 3rd party APIs</li>\n</ul>\n"}, {'answer_id': 8570, 'author': 'Lars Mæhlum', 'author_id': 960, 'author_profile': 'https://Stackoverflow.com/users/960', 'pm_score': 1, 'selected': False, 'text': "<p>Ouch. Please don't extend Interfaces.<br>\nAn interface is a clean contract that a class should implement, and your usage of said classes <strong>must</strong> be restricted to what is in the core Interface for this to work correctly.</p>\n\n<p>That is why you always declare the interface as the type instead of the actual class.</p>\n\n<pre><code>IInterface variable = new ImplementingClass();\n</code></pre>\n\n<p>Right?</p>\n\n<p>If you really need a contract with some added functionality, abstract classes are your friends.</p>\n"}, {'answer_id': 13514, 'author': 'Scott Dorman', 'author_id': 1559, 'author_profile': 'https://Stackoverflow.com/users/1559', 'pm_score': 2, 'selected': False, 'text': '<p>There is nothing wrong with extending interfaces, in fact that is how LINQ works to add the extension methods to the collection classes.</p>\n\n<p>That being said, you really should only do this in the case where you need to provide the same functionality across all classes that implement that interface and that functionality is not (and probably should not be) part of the "official" implementation of any derived classes. Extending an interface is also good if it is just impractical to write an extension method for every possible derived type that requires the new functionality.</p>\n'}, {'answer_id': 13563, 'author': 'Zooba', 'author_id': 891, 'author_profile': 'https://Stackoverflow.com/users/891', 'pm_score': 2, 'selected': False, 'text': '<p>I see separating the domain/model and UI/view functionality using extension methods as a good thing, especially since they can reside in separate namespaces.</p>\n\n<p>For example:</p>\n\n<pre><code>namespace Model\n{\n    class Person\n    {\n        public string Title { get; set; }\n        public string FirstName { get; set; }\n        public string Surname { get; set; }\n    }\n}\n\nnamespace View\n{\n    static class PersonExtensions\n    {\n        public static string FullName(this Model.Person p)\n        {\n            return p.Title + " " + p.FirstName + " " + p.Surname;\n        }\n\n        public static string FormalName(this Model.Person p)\n        {\n            return p.Title + " " + p.FirstName[0] + ". " + p.Surname;\n        }\n    }\n}\n</code></pre>\n\n<p>This way extension methods can be used similarly to XAML data templates. You can\'t access private/protected members of the class but it allows the data abstraction to be maintained without excessive code duplication throughout the application.</p>\n'}, {'answer_id': 14273, 'author': 'Fredrik Kalseth', 'author_id': 1710, 'author_profile': 'https://Stackoverflow.com/users/1710', 'pm_score': 1, 'selected': False, 'text': "<p>I see a lot of people advocating using a base class to share common functionality. Be careful with this - you should favor composition over inheritance. Inheritance should only be used for polymorphism, when it makes sense from a modelling point of view. It is not a good tool for code reuse.</p>\n\n<p>As for the question: Be ware of the limitations when doing this - for example in the code shown, using an extension method to implement GetChildren effectively 'seals' this implementation and doesn't allow any IHaveChildren impl to provide its own if needed. If this is OK, then I dont mind the extension method approach that much. It is not set in stone, and can usually be easily refactored when more flexibility is needed later.</p>\n\n<p>For greater flexibility, using the strategy pattern may be preferable. Something like:</p>\n\n<pre><code>public interface IHaveChildren \n{\n    string ParentType { get; }\n    int ParentId { get; }\n}\n\npublic interface IChildIterator\n{\n    IEnumerable&lt;IChild&gt; GetChildren();\n}\n\npublic void DefaultChildIterator : IChildIterator\n{\n    private readonly IHaveChildren _parent;\n\n    public DefaultChildIterator(IHaveChildren parent)\n    {\n        _parent = parent; \n    }\n\n    public IEnumerable&lt;IChild&gt; GetChildren() \n    { \n        // default child iterator impl\n    }\n}\n\npublic class Node : IHaveChildren, IChildIterator\n{ \n    // *snip*\n\n    public IEnumerable&lt;IChild&gt; GetChildren()\n    {\n        return new DefaultChildIterator(this).GetChildren();\n    }\n}\n</code></pre>\n"}, {'answer_id': 38494, 'author': 'Emperor XLII', 'author_id': 2495, 'author_profile': 'https://Stackoverflow.com/users/2495', 'pm_score': 4, 'selected': True, 'text': '<p>I think the judicious use of extension methods put interfaces on a more equatable position with (abstract) base classes.</p>\n\n<p><br/>\n<strong>Versioning.</strong> One advantage base classes have over interfaces is that you can easily add new virtual members in a later version, whereas adding members to an interface will break implementers built against the old version of the library. Instead, a new version of the interface with the new members needs to be created, and the library will have to work around or limit access to legacy objects only implementing the original interface.</p>\n\n<p>As a concrete example, the first version of a library might define an interface like so:</p>\n\n<pre><code>public interface INode {\n  INode Root { get; }\n  List&lt;INode&gt; GetChildren( );\n}\n</code></pre>\n\n<p>Once the library has released, we cannot modify the interface without breaking current users. Instead, in the next release we would need to define a new interface to add additional functionalty:</p>\n\n<pre><code>public interface IChildNode : INode {\n  INode Parent { get; }\n}\n</code></pre>\n\n<p>However, only users of the new library will be able to implement the new interface. In order to work with legacy code, we need to adapt the old implementation, which an extension method can handle nicely:</p>\n\n<pre><code>public static class NodeExtensions {\n  public INode GetParent( this INode node ) {\n    // If the node implements the new interface, call it directly.\n    var childNode = node as IChildNode;\n    if( !object.ReferenceEquals( childNode, null ) )\n      return childNode.Parent;\n\n    // Otherwise, fall back on a default implementation.\n    return FindParent( node, node.Root );\n  }\n}\n</code></pre>\n\n<p>Now all users of the new library can treat both legacy and modern implementations identically.</p>\n\n<p><br/>\n<strong>Overloads.</strong> Another area where extension methods can be useful is in providing overloads for interface methods. You might have a method with several parameters to control its action, of which only the first one or two are important in the 90% case. Since C# does not allow setting default values for parameters, users either have to call the fully parameterized method every time, or every implementation must implement the trivial overloads for the core method.</p>\n\n<p>Instead extension methods can be used to provide the trivial overload implementations:</p>\n\n<pre><code>public interface ILongMethod {\n  public bool LongMethod( string s, double d, int i, object o, ... );\n}\n\n...\npublic static LongMethodExtensions {\n  public bool LongMethod( this ILongMethod lm, string s, double d ) {\n    lm.LongMethod( s, d, 0, null );\n  }\n  ...\n}\n</code></pre>\n\n<p><br/>\nPlease note that both of these cases are written in terms of the operations provided by the interfaces, and involve trivial or well-known default implementations. That said, you can only inherit from a class once, and the targeted use of extension methods can provide a valuable way to deal with some of the niceties provided by base classes that interfaces lack :)</p>\n\n<hr>\n\n<p><strong>Edit:</strong> A related post by Joe Duffy: <a href="http://joeduffyblog.com/2010/02/09/extension-methods-as-default-interface-method-implementations/" rel="nofollow noreferrer">Extension methods as default interface method implementations</a></p>\n'}, {'answer_id': 206325, 'author': 'Scott McKenzie', 'author_id': 26625, 'author_profile': 'https://Stackoverflow.com/users/26625', 'pm_score': 1, 'selected': False, 'text': "<p>Rob Connery (Subsonic and MVC Storefront) implemented an IRepository-like pattern in his Storefront application. It's not quite the pattern above, but it does share some similarities.</p>\n\n<p>The data layer returns IQueryable which permits the consuming layer to apply filtering and sorting expression on top of that. The bonus is being able to specify a single GetProducts method, for example, and then decide appropriately in the consuming layer how you want that sorting, filtering or even just a particular range of results.</p>\n\n<p>Not a traditional approach, but very cool and definitely a case of DRY.</p>\n"}, {'answer_id': 1859130, 'author': 'Abdo', 'author_id': 226255, 'author_profile': 'https://Stackoverflow.com/users/226255', 'pm_score': 0, 'selected': False, 'text': '<p>I needed to solve something similar:\nI wanted to have a List&lt;IIDable&gt; passed to the extensions function where IIDable is an interface that has a long getId() function.\nI tried using GetIds(this List&lt;IIDable&gt; bla) but the compiler didn\'t allow me to do so.\nI used templates instead and then type casted inside the function to the interface type. I needed this function for some linq to sql generated classes. </p>\n\n<p>I hope this helps :)</p>\n\n<pre><code>    public static List&lt;long&gt; GetIds&lt;T&gt;(this List&lt;T&gt; original){\n        List&lt;long&gt; ret = new List&lt;long&gt;();\n        if (original == null)\n            return ret;\n\n        try\n        {\n            foreach (T t in original)\n            {\n                IIDable idable = (IIDable)t;\n                ret.Add(idable.getId());\n            }\n            return ret;\n        }\n        catch (Exception)\n        {\n            throw new Exception("Class calling this extension must implement IIDable interface");\n        }\n</code></pre>\n'}, {'answer_id': 2025433, 'author': 'Jerry Liu', 'author_id': 240951, 'author_profile': 'https://Stackoverflow.com/users/240951', 'pm_score': 2, 'selected': False, 'text': '<p>A little bit more. </p>\n\n<p>If multiple interfaces have the same extension method signature, you would need to explicitly convert the caller to one interface type and then call the method. E.g.</p>\n\n<pre><code>((IFirst)this).AmbigousMethod()\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/8042', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/905/']