Stories about Software


Why I don’t like C# extension methods

When I first became aware of the Extension Method in C#, my reaction was similar to that of a lot of people–I thought it was a pretty neat trick. For anyone not familiar with extension methods, they are a construct introduced in C# along with LINQ to allow ‘extension’ of a class. Here’s an example:

What’s going on behind the scenes here is that Microsoft introduced syntactic sugar on standard static methods. An extension method is really just a static method, and as far as the compiler is concerned, the client code is no different than it would be if you called “Extensions.GetWordCount(str);”

The advantages are immediately obvious. You can abstract verbose and redundant common idioms into these methods, favoring instead descriptive terminology. You can make it look as though GetWordCount() is a method of string, even though it isn’t. This means that, done right, you can create the appearance of enhanced classes without modifying the classes themselves. If you keep these methods well organized, they seem a natural enhancement to the language. And perhaps the most powerful thing of all is that you can extend library classes that are sealed or have non-virtual methods, or you can supply enhancements to your own API for others without the risk of introducing breaking changes.

But in spite of those benefits, something bothered me about this idea. I couldn’t quite put my finger on it for a long time. The drawbacks that one that might see in a google search or realize on his own include decoupling class-specific functionality from that class (i.e. violating encapsulation) and the fact that you’re favoring free-floating static utility over instance methods. There is also the possibility for naming collisions if you write an extension method with the same signature as an instance method. There is the confusion that one might experience not knowing through intellisense whether you were dealing with a native method of some class or an afterthought that somebody tacked on. But all of those drawbacks seemed to have reasonable counterpoints, and none of them really address the notion of enhancing bad APIs that you’ve been given or putting out your own extensions to preserve reverse compatibility.

So, as an experiment, I developed a little utility and decided to load up on extension methods to really try them out, having previously only been a client of them. I was writing a bunch of things out to an HTML file and using the XDocument API to do it (taking advantage of the fact that HTML is conceptually a subset of XML), so I thought I had the perfect opportunity. I added a bunch of extension methods for XElement that would do things like create tables, styles, and other HTML constructs. I would do something like myXElement.CreateTableOutline(rows, columns, title, headerColor);

It was pretty slick. And, as I did it, I found that these extension methods begat more extension methods for other things. Pretty soon, I had the cleanest, easiest to read code that you could ever want in a data access object. It read like a book, not like code: “Element.CreateTableWithThis()”, and, “Element.PopulateTableWithThat();” Best of all, it looked like a beautiful object-oriented design.

And, at that moment, the thing I couldn’t put my finger on that had been bothering me leaped into full view. It looked like object-oriented design. Extension methods, as I mentioned earlier, are just stateless (hopefully) static methods gussied up to look like instance methods. And, stateless static methods are really just procedural constructs that exist outside of any application state at all–the much younger brother with a striking resemblance to something in the C world that you might call “utils.c” and populate with 8000 functions that just didn’t fit anywhere else.

The whole time, I had been making my code increasingly procedural. I had been moving ugly functionality out of my instances and putting it into the blob of stateless static functionality, prettying it up by making it a series of extension methods. Rather than create some kind of HtmlElement class that inherited from or wrapped an XElement, I created a laundry list of extension methods that could easily have been called “public static class HtmlUtils”. Taken to its logical conclusion, I could write an entirely procedural application with nothing but extensions of existing classes. I realize that nobody is likely to do that, but it is interesting that such a thing is possible and that you can gravitate toward it without realizing it.

And that is the crux of what bothered me all along. Here, we have a brand, spankin’ new language feature introduced to an object-oriented language that gives users the ability to make their code substantially more procedural while making it look substantially more like a clean object-oriented design. Extension methods are the ultimate in deodorant for a code smell. If you venture down that rabbit hole, you’ll never ask yourself why you’re increasingly favoring static utils methods instead of object-oriented design because you will fool everyone else and even yourself into thinking that you are using object-oriented principles.

The denouement of my little story was that I systematically removed all of the extension methods. In their place, I created a series of small methods on a common base class and factored some of the functionality into value objects and small inheritance structures that defined HTML constructs. The result wasn’t as pretty, and I didn’t get the fluent interface feel, but the way I see it, I gave up high fructose corn syrup for fresh-squeezed orange juice. The new design may have required that I add a few classes, but I now have the ability to extend CreateTable() in sub-classes rather than adding a bunch of additional static methods for that functionality. With stateless static methods, you can’t inherit base classes or implement interfaces to take advantage of polymorphism.

I’m not advocating that everybody swear off extension methods (or really advocating much of anything), but rather explaining why I don’t like the construct and choose not to use it. Since my discovery, I’ve paid closer attention to how other people use extension methods. I’ve seen them used to circumvent the compiler for preventing circular dependencies. I’ve seen them used to ‘extend’ functionality in the same namespace where it would have been perfectly reasonable just to add a method to the class itself. I’ve even seen them used to hold and alter global state. And I’ve also seen them used somewhat reasonably.

But, at the end of the day, extension methods are the cousin of the singleton in that they both have an unanticipated side effect. That side effect is a vehicle for developers who are forced to develop in OO languages, but have always carried the torch for procedural programming, to sneak back to visit the ex without anyone knowing. In both cases, for the OO programmer, I would advise a bit of frank examination of the motivations for using the construct. Is it because extending the class (or forcing one global instance) is the only/best possible approach, or is it because it’s easier and faster than taking a hard look at your design or object graph? If it’s the latter, you could be heading for some headaches down the road.

  • There is the confusion that one might experience not knowing through intellisense whether you were dealing with a native method of some class or an afterthought that somebody tacked on.

    Visual Studio 2010 intellisense denotes extension methods as such.

    • That’s a nice addition. I had thought that the “(extension)” that you see in intellisense was the result of standard C# libraries having it added to their XML comments, but I just ran an experiment, and this appears to happen automatically for any extension method. That is, I created an extension method with no documentation that takes one of my classes as a parameter and intellisense shows me “(extension)” automatically. Nice catch.

  • “Extension methods are the ultimate in deodorant for a code smell.”
    => Fantastic line 🙂

    I’ve done a lot of Ruby development as well (a dynamic language) and here you don’t really care about clashes and all the stuff you start out mentioning. That’s really the nature of dynamic languages, but the whole argument about state is dead on!

    We think we’re doing our code more OO, but in fact we should rather look into the “good ol’ inheritance thing”, constructs that lived before all the syntactic sugar the c# compiler gets more and more of.

    • I’m glad you liked it 🙂

      I poked around a little when I was writing this post to see what other people thought of extension methods and saw Ruby mentioned rather prominently. I hardly have any experience with Ruby, but I do understand the nature of a dynamic language and how that might interact with the extension method construct. I’m glad to see that what I was talking about does seem to transcend languages, and I’m glad that I’m not the only one who sees it and thinks that some caution is in order. I do personally like a lot of things they’re adding to C# as they go, but this one seems a little iffy to me because of how it seems to beg for procedural code in an OO language.

    • Kevrell

      I suppose that sounds and smells just about right.

  • Alethia Barnhardt

    Couldnt agree more with that, very attractive article

    • Thanks for the kind words — glad you enjoyed.

  • Verda Keniry

    If you are open to having a guest blog poster please reply and let me know. I will provide you with unique content for your blog, thanks.

    • If you want to send me a link to a technical blog that you write or else send me a bit about your technical background, I’m happy to consider it. The more the merrier.

  • score

    Hi there, I found your blog via Google while searching for a related topic, your site came up, it looks good.

  • flagyl

    Really interesting blog, keep up the good work!

  • Pingback: Basic Unit Testing with JUnit for C# Developers 2 | DaedTech()

  • This is great article. Many thanks Erik for this. I was searching for language comparison and wanted to know what languages are providing features like C#. my observation has always been that C# team finds out architectural patterns being used in industry in version n, and, adds them as feature in version n + 1. I currently have 5+ years of experience in .Net (c#) but I want to master another language. doesnt have to be OO. doesnt have to have LOTS of features (syntatic sugar ;)) but one intelligent enough to allow me create extensible, maintainable, componentized webapps. can you please suggest?

    • Glad you liked it, and thanks for the kind words. As for other languages to learn with a web focus, Ruby seems to be all the rage these days, particularly among clean coder types. I don’t know it myself, but if I were going to pick one out to learn right at this moment, I’d probably give it a look.

  • EvaO

    Funny how often Ruby is mentioned in the comments considering how Ruby goes far beyond extension methods and even allows you to override methods in classes already defined. Extension methods are mixins with safety scissors (which are in turn multiple inheritance with gloves on). The only commonly used OO language I can think of that doesn’t use extension methods, mixins, or multiple inheritance is Java. There is no dearth of ugly util classes in Java. I have never seen people use extension methods as fancy utils as much as I’ve seen people use util classes as regular ugly utils in Java, so I’m not convinced C# “encourages” procedural programming. I would wager that the folks misusing extension methods would use procedural programming just as much in any language. The difference is in how pretty it looks when they’re done.

  • Danny Miller

    While I am not a big fan of overusing extension methods, I don’t find your reason to be compelling. There are a couple reasons for that.

    1. From day one, I and the other developers around me understood the static utility nature of extension methods and therefore used them with proper moderation.
    2. In object oriented languages like C# and Java, all instance methods are really no more than static methods accepting a first parameter of “this”. Seriously. It is just syntactic sugar that you write them the way you do. After all, every instance of a class does not hold a whole new definition of its functions… rather they are stored in a static class definition and provided the instance as context. So extension methods and instance methods do not differ in basic concept, only slightly in syntax and in where the compiler allows the code to live.

    Again, I don’t use extension methods a whole lot. While they can quickly and easily add powerful and expressive capabilities, I have found more traditional OO approaches to offer what I need.

    • It was a few years ago that I made this post, and at the time I was surrounded by people who abused the construct heavily. In the time since then, I’ve come to find it convenient to add extension methods for third party APIs that I find lacking, particularly in test projects. I’ve also offered them as extensions of APIs that I’ve written. So I definitely get (1).

      Your point (2) is confusing to me. I’m talking about syntactic sugar in the sense of one source code construct (extension methods) masking the nature of another (static utils methods). You’re talking referring to the way the compiler implements things as “syntactic sugar” and jumping a level of abstraction. Using this sort of reasoning, I could say that object orientation and even while and for loops don’t matter because it’s all just “syntactic sugar” over assembly instructions and branch/goto. An applications programmer doesn’t care what register the “this” pointer is passed in or how it gets there, but he most certainly does care that there is a language construct that causes static methods to appear at casual inspection to be instance methods. And in terms of application design, there most certainly and unequivocally is a huge difference between static and instance methods (participation in polymorphism, just for starters).

      • Danny Miller

        I agree with you, maybe I was jumping a level of abstraction that most people would not. And there’s no arguing that at the language level there’s a difference between instance and static methods. For being a young guy, though, I often do have that feeling that it is unfortunate that people don’t realize object oriented programming is just a prettier language-supported (or enforced) syntax for what you could already do in non-objected oriented languages. I love OO, live in it every day, and like the extra work the compiler does for us, but I don’t drink the Kool Aid 🙂

        It’s very relevant that you bring up polymorphism, because while I didn’t list any of my personal top downsides to extension (aka static) methods in the previous comment, the lack of polymorphism would be my #1.

        • I looked for it over the weekend, but I couldn’t find the link to something I thought you might enjoy. It was a talk where Bob Martin showed an example of inversion of control using C and pointed out that you didn’t need OOP to have good “OOP design” so to speak — that good design transcends paradigms.

          • Danny Miller

            That would indeed be interesting! I know some big Uncle Bob fans around here 🙂

  • Pingback: Hiding your dependencies – an expert programmer’s guide | Martin Doms()

  • Pingback: Help Yourself To My Handy Extension Methods | DaedTech()

  • bingbingwa

    Just finished a c# book where extensions were crucial to some of the design patterns. You do use design patters, don’t you?

    • I’m not really sure I understand the motivation for the question about whether I use design patterns or not. I mean, it’s hard to infer tone from text, but this comes off as, “I saw someone use extension methods as part of the implementation of a design pattern, so if you don’t use extension methods, you must not use design patterns.” This is a pretty hard sell, given that the Gang of Four design patterns and presentation layer standards like MV* predate the release of extension methods and, in some cases, even C#. (Assuming that’s what you meant and that I’m not misreading your implications — apologies if I am)

      As I said in my exchange with Danny Miller, my opinion on this language construct has softened in the three years since I wrote this, and I tend to find it handy, in smallish doses for hiding clunky APIs that are forced on me and I find it nice to use it the way the language authors did with Linq — separating the core functionality and add-ons when I’m releasing APIs.

      That being said, it’s hard for me to conceive of an extension method mattering to any well known design pattern, since they’re just syntactic sugar on static methods. You could accomplish any design pattern implementation you wanted by using static methods rather than extension methods.

      • bingbingwa

        using static methods rather than extension methods… sounds like a good topic to write about next. I’d like to learn more about this.

        • I can certainly write up my take on the subject. I’ll put a placeholder in my drafts folder and write a bit about it when I get a chance (and respond again to this comment when I do).

          • bingbingwa

            Sounds good!

  • Hi Erik,

    I have a good use case for extension methods: On any object that has access to the application cache in an MVC application. The cache is dynamic and it can soften some of the overly sweet syntactic sugar that is at the static of extension methods.

    I have been using extension methods in a C# Class library that I intend to share with some developers at the office. The main idea for the library is that it contains a IWebAppManager interface which specifies some core functionality that is meant to be implemented by a concrete class. Of course there is a lot of utility function specified as well that is implemented by an abstract class.

    I’ve also provided a concrete class they can use if they don’t want to code to the IWebAppManager interface. My default class can instead be configured at run-time and achieves almost all of its functionality via the decorator pattern, decorating the class with Interface members that can be invoked dynamically at run-time to achieve the core-functionality.

    A concrete instance of the IWebAppManager is meant to be instantiated in the Application_Start method, by passing the System.Web.HttpApplication instance to the init method. If the init method of the Abstract class is used, the instance will add itself to the cache of the application with a key derived on the reverse domain and package name of the IWebAppManager.

    This allows for a assortment of extension methods like the following:

    public static IWebAppManager GetWebAppManager(this HttpApplicationState webApp){
    return (IWebAppManager) webApp[IgniteWebUtils.Manager.AbstractWebAppManager.CACHE_KEY_iwebAppManager];

    With the above extension method, anyone on my team can, from various places, get a handle on the Singleton instance of the IWebAppManager and start calling various utility methods.

    When concrete instances achieve almost all of their functionality via the decorator pattern using other instance of interfaces that can be dynamically invoked at run time via configuration or rather specified in the code if you hate the very idea of run-time exceptions.

    Anyway, those are just my thoughts of when it is good. In most places I completely agree that extension methods are anti-OO, but when an object has access to a cache shared by nearly everything in the application, you can do some really productive things.

    P.S. On the note of OO vs procedural, I have to admit that I do enjoy walking the line. Yes, procedural code is harder to maintain and understand, and yes, it is easier to do wrong, however, if you do it right, you can achieve a lot of performance gains.

    P.P.S Extension methods are 100% ok for string and other immutables in my opinion.

    • When I wrote that post, the language feature was pretty new and people were using it to do all manner of horrifying things in the code base I was working with at the time. That certainly colored my take back then (and really, I think there’s a period of “I can so I will” with any new language feature). It’s not hard for me to imagine that people will find use cases for the feature that make code simpler or more readable.

      As for performance gains, I tend to gravitate toward making things as readable as possible until such time as someone is actually screaming about performance, and that someone is a person paying for the software. In other words (less tongue in cheek) I don’t think about performance at all when writing code and don’t much care about it — if the code needs to be fast in a critical place, I’ll automate that requirement with a test and worry about it then.

  • vishok
  • zak willis

    This is a worthy article, and some valid points.

    If your entire codebase is filled with hundreds of extension methods then you have a point. However, Extension methods could be considered a helpful tool in the evolutionary life cycle of TDD/conceptual before understanding what the application is supposed to do and then moving these static helpers into a class that gives it context – which is what you did. So right now, I am writing a class to manage saving data from a POCO (more complex than that). So I started by encapsulating any helperesque functionality inside that class, it became clear that the class was becoming bloated and becoming a blackbox. On the onehand, the class has a singularish responsibility but needs some additional information to perform its task, on the other, I would like to be able to test some of the logic it is using to help it perform its task. So I could move all functions to a new class called PocoSaverHelpers (name changed to protect the innocent) which is what I am doing and actually agrees with your article, but I then have quite tight coupling between these two classes without clarity that the functionality genuinely needs to sit inside PocoSaverHelpers, but do have the capability to test these independently. Whilst I am still figuring out what my code should do, it could be equally as useful to use some extension methods. I could then write a simple suite of demonstration unit tests (unit test being more of a demonstration of functionality). A simple example could be var fileNameToWrite = poco.first().filename.GetFileExtension(); Assert.AreEqual etc… Some people might say, ugh, you will end up with thousands of unit tests using extension methods but that really is a question of common sense.

    I am not advocating using extension methods is a requirement in the SDLC.
    In reading your article, what you actually did was to create extension methods before refactoring once you had a better understanding of what your code was supposed to do. This is normal, and I think that extension methods have their place and it could have been more comprehensive to also describe this type of scenario. It can be convenient to have a simple set of extension methods until you figure out where they should ultimately reside.

  • Realtebo ✔ᵛᵉʳᶦᶠᶦᵉᵈ

    100% ok
    Or I extend Or I create a static util class, both I want to avoid to create something as a static utils than lokks like an extended class (or viceversa. … )

  • sm


  • Panos Roditakis

    Extension methods are dangerous when developers implement business logic inside them.
    For example I was extending NopCommerce the other day and wanted to override the cart.RequiresShipping() method. When I tried to do so without changing their core code (.cs file), I was disappointed to see that it was an extension method used in 20 different places and the override would remain a dream.

    So, once again, it’s not the tools fault, but the way they are used.

    • In the years between writing this and now, my view has become more nuanced, but what you’re describing, business logic in extension methods… yikes. I still would most certainly not be a fan of that.

  • Ronak Thakkar

    Extension methods are just syntatic sugar on static methods and they are bound at compile time and not based on instance type on run time. It cannot be over-ridden and does not support polymorphic scenario. This can create big problems. I created some extension methods as they were easy but after some time I realized that I had to override them with another implementation which is not possible. Hence I have to remove all extension methods. Hence as a general principle always create your software that can be extended and Extension methods will block that. So I would never dare to use Extension methods again.

  • steve

    I don’t agree completely. Extension methods are not the same as a built-in public or internal class methods but pretty close. C# is about productivity. When you use a class, you often have to interact with other classes which the first class knows nothing about.
    Your choices are to use an extension method in a comfortable namespace or write another class to encapsulate how those two classes interact.
    static bool ResultOfEncounter( this ClassA agent this ClassB provocateur)
    // special knowledge of both of these classes and how they might interact.
    Ultimately a better implementation might be some other class that has visibility of these 2 classes with some methods. But that forces instantiation so that has to be carefully designed. And multiple contexts might want to utilize those methods and/or encapsulated classes as well so that increases ambiguity of design.

    Long term, formally defined encapsulation is much better for extensive re-use.. But as an intermediate step it’s satisfactory to implement a properly scoped static extension class which can be observed as a vulnerable code-point but sort of productivity step.
    Let’s say your context (ContextA) presents 20 classes all of which must interact with ClassA (which properly, knows nothing of those classes) and maybe ContextB must interact with 10 of those 20 interactions and there’s ContextC, which isn’t defined yet, which you know will need access. In this case, a carefully scoped static extension class (or several) seems to be a satisfactory intermediate step. Later, evolution of the design might migrate those extension methods to encapsulating classes and then, yes, there would be some adjustment in existing code if it wanted to take advantage of that design. But I don’t know how to avoid that, actually, either way.

  • I wouldn’t say, “I don’t like extension methods” because you probably use them all the time and love the ones you use, even if you don’t know you are using them. For example, you can’t love LINQ without loving extension methods.

    Extension methods were developed with a purpose. When used for that purpose, extension methods are phenomenally power tools to enhance any C# project.

    However, you have a point, that like any tool, it can be used incorrectly. Many of the uses you have mentioned may or may not be good purposes.

    Purpose 1: Adding methods to sealed classes.
    There are many classes that can’t be inherited from, namely “string”. I could have been misinformed, but I was told that extending the sealed “string” object was the #1 reason extension methods were created.

    Purpose 2: Adding methods to POCO objects.

    When you are creating objects that must be POCO objects, they shouldn’t have methods. If they POCO objects need methods, those methods are better provided as Extension methods. You can argue that a Utils class better, but it isn’t. If the utils class is static, then you lose the syntactical sugar, if the util class is not static, then you have to instantiate it first and add more lines of code.

    Some of your arguments also don’t hold water. Not everything fits in an object oriented design. Object Oriented design is not always better than procedural design. I usually prefer object-oriented design, but in the end, everything is procedural. Object-oriented design is just syntactical sugar, hiding your procedural assembly code the the IL compiles to. So your argument that it moves you from Object-oriented to procedural and that is a bad thing is questionable at best.

    Now, I’ll add to the last paragraph by remind you that extension methods are Object-Oriented. They are static members of a static object. Extension methods lead one to have two objects for a class where before there was only one. More smaller objects with single responsibilities and more methods with single responsibilities lead to better decoupled code. For example, Person and PersonExtensions. Now, you don’t ever have to type out PersonExtensions, but just because you don’t have to doesn’t mean you can’t.

    You also said: ” It read like a book, not like code” then you continued like that was a bad thing. This is a huge feature. Code sucks to read. Readability is extremely important.

    Then you made this comment : “The result wasn’t as pretty, and I didn’t get the fluent interface feel, but the way I see it, I gave up high fructose corn syrup for fresh-squeezed orange juice.” I disagree, with your analogy. In reality, you gave up readable code for less-readable code.

    Another great feature of extension method is unit tests, especially when refactoring code that breaks the 10/100 rule. As a developer, I often inherit legacy systems with bad methods that are hundreds, sometimes thousands of lines long. Writing a Unit Test is not really doable for such a method. Refactoring without unit tests is like playing Russian roulette with bugs. You can break up the procedural code into small parts quite quickly with extension methods. Because they are small, those parts are usually immediately unit testable.

    I could go on, but really, I am not trying to convince you to change your mind. I am perfectly happy for you to have a different opinion than me. Especially since your reasoning is quite thorough and thought out. You sound like a great developer, who I’d likely hire, if a position on my team were open and you applied. I just thought I would provide your readers an alternate point of view.

  • Aluan Haddad

    I realize from reading the comments and responses that your views have evolved over the years, however I think you are missing a few fundamental points.

    1. You seem to be under the impression that C# is an object oriented language. C# like most programming languages is a multi-paradigm language. It favors a number of Object Oriented techniques but it also has higher order functions, generics, and a myriad of procedural constructs and lots of other things that are not Object Oriented.

    If you have ever been told that C#, C++, or even Java “is an Object Oriented Programming language”, it was either disingenuous marketing or, more likely, bad teaching. Of these three languages (which are just a few examples of course), only Java tries to be a pure Object Oriented language and it completely fails at this by being less Object Oriented than either C# or C++.

    2. You seem to indicate that statelessness is a bad thing. This simply not true. It is true that people can be overly zealous about removing mutable state, to there point where it isn’t practical or useful, but less mutable state is always better. It is easier to reason about code that doesn’t have side effects, that is to say code that is expressed as transformations.

    Precisely because extension methods do not have access to the internal state of the object, they cannot violate encapsulation.

    Obviously we can do really nasty things in extension methods, like cache objects in a ConcurrentDictionary or CWT, but this is rare, and doing so in extension methods is awkward and sticks out like a sore thumb during code review.

    3. You write

    “Pretty soon, I had the cleanest, easiest to read code that you could ever want in a data access object. It read like a book, not like code: “Element.CreateTableWithThis()”, and, “Element.PopulateTableWithThat();” Best of all, it looked like a beautiful object-oriented design.”

    These all sound like good things to me.

    “Pretty soon, I had the cleanest, easiest to read code that you could ever want in a data access object. It read like a book, not like code: “Element.CreateTableWithThis()”, and, “Element.PopulateTableWithThat();””

    That is a great thing! Seriously code should aspire to be readable above all else. Bravo for making it so.

    “Best of all, it looked like a beautiful object-oriented design.”

    Again, this is great. You have abstracted!

    I don’t care that there is no hierarchy of classes underneath, I don’t need that.
    When I see your code and your code does what it says, not says how it does, it is a pleasure to read.

    What we really mean here is that it looks like method call on objects, which is another way of saying that it reads in left to right, subject verb object order. This is a very good thing (native English makes me biased of course but that is a different subject).

    4. You write

    “The new design may have required that I add a few classes, but I now have the ability to extend CreateTable() in sub-classes rather than adding a bunch of additional static methods for that functionality. With stateless static methods, you can’t inherit base classes or implement interfaces to take advantage of polymorphism.”

    While this is by far the most compelling argument you make, it also brings us full-circle.
    Using extension methods is sometimes limiting because, as you also point out, it does not implement interfaces. One might well ask why? The reason is that the dispatch mechanism is static (see Scala for a language with non-static extensions that implement). This is by far the biggest drawback of extension methods, but it only matters on a case by case basis.

    I think this has nothing to do with extension methods but rather takes us back to the question of what kind of language C# actually is. Obviously Object Oriented Programming is a paradigm supported by C#. But in C# methods are, by default non-virtual! The was an intentional design decision due to the complexity and uncertainty introduced by virtual method calls, especially on stateful objects, as a system evolves. Just like stateless methods, static dispatch is easier to reason about, but can sometimes be limiting. The same can be said of deep hierarchies. If we program to interfaces, hierarchies are less likely to grow deep.

    Regardless, C# gives us the capability to design as we see fit, and that includes making use of complex hierarchies where we see fit. It also allows us to take advantage of syntactic abstraction, like extension methods, to make performing simple tasks (for X x, take a string representation of x) in a simple way without facing the unnecessary awkwardness of creating additional types or putting methods that are used in just a few places as a first class member of X.

    Extension methods are great for all sorts of things. They provide natural, type semantic organization for utility methods that either should not or can not be used be in the target type. Further, the target type can be abstract which is extremely beneficial.

    They allow enriching existing types with new functionality that can only be made available by referencing and importing specific assemblies. This means that expensive operations, that would be part of type T if type T were in assembly A, but cannot be because type T needs to be available to consumers who cannot afford to rely on A, to take gain that functionality by bring a namespace or type from assembly A into scope.

  • RenniePet

    I love your writing style. If you ever get tired of programming you should become an author.

    • Thanks! That means a lot. And, for what it’s worth, that’s kinda the plan. If you visit the site again, check out the sidebar at the right to see the book I’m writing — Developer Hegemony. After we publish that, I’m contemplating a foray into fiction.

  • Michiel Huygen

    You describe that use of extension methods makes your code more procedural and less object-oriented. Did you consider the fact that extension methods can also be seen as a way to introduce Functional programming concepts into C#. If you look at the LINQ or Reactive extensions libraries, extension methods are mainly used to achieve a combination of functional programming and object oriented programming that i rarely see in other languages.

    I therefore think that use of extension methods in itself is not a code smell, but using them to do procedural programming is. What do you think about this?

  • cyrille

    Thank you for your article even if I’ll keep using the extensions methods exactly because you can have a fake turn-around a big limitation of C# : the single inheritance.

    By adding extensions methods to interfaces, generic ones if possible, you can reach an aspect-oriented design, where adding an interface gives your objects some pre-determined behaviour. Mainly, it attaches the tools that you usually need where you use them, without reinventing the wheel anytime you change the implementation, helping with maintaining the code.

    It is not as powerful as a real multiple inheritance, but it helps.

    It obviously comes with some of the drawbacks of “multiple inheritance” like names conflicts, but relying on interfaces for your objects interactions keeps you out of jail.

    However, you gave me the only real trade-off I have seen so far, which is the lack of customization in inherited classes. “With stateless static methods, you can’t inherit base classes (..) to
    take advantage of polymorphism.” This is a serious argument and I thank
    you for this one.

    Now instead of a binary choice, one can keep both worlds ongoing: use them for the routines, and keep your business logic in the concrete class. (cf comment by Panos Roditakis)