Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.

Channels ▼

Christopher Diggins

Dr. Dobb's Bloggers

Extension Methods in C#: cool but at what cost?

April 18, 2009

Why I tend to shy away from extension methods in C#, despite their high convenience factor.

Extension methods are a feature of C# 3.0 (and somewhere in the caverns of my mind, another language is yelling that it supports it too) that allow a programmer to add new methods to an already defined class or interface, even if you don't have the source.

So say for example that I am writing a utility method that counts the number of instances of a specific character in a string. I could write it as an extension method as follows:

static class TheNameOfThisClassDoesntMatter { 
  static String CountChars(this String self, char c) {
    int r = 0;
    for (int i=0; i < self.Length; ++i)
      if (s[i] == c)
        r += 1;
    return r;    

Now  I can the methods "CountChars" on a string instance, just as if it was an ordinary method. E.g.

string s = "abcba";
int n = s.CountChars('a');

More on extension methods can be found here on MSDN.

Now, why don't I use them? Extension methods violate an important prinicple of software engineering: code cohesion. In other words "portions of code which shares responsibility should be kept together".

 To consider whether or not a design decision is a good idea, I like to do a thought experiment where I imagine using a feature more and more heavily, until it becomes ridiculous. So in doign this I imagine code if we just defined none of our methods in the classes altogether. Of course, no sane person would do that (which means about 5% of programmers will try), so we have to look at the middle ground. It seems to me that even moderately heavy usage of extension methods, can render code unneccesarily hard to manage.

For those familiar with C#, a good example of extension methods going a bit amok, is when we use Intellisense with a class that implements IEnumerable. In C# 3.0 the System library now introduces a whole lot of new interesting extensions methods.

One really disturbing extension method is called "Count" (see it here on MSDN). Seems harmless, but it is "O(N)". This is obviously not the one you want in most cases, when you are working with arrays or lists (as is the case 90% of the time). It is intended for IEnumerable classes that don't explicitly provide a Count or Length property. I can just imagine all of the coding disasters happening to junior C# programmers around the globe.

Any thoughts? Like to use extension methods? If you have to maintain someone else's code, how much would you let them get away with using extensions, before you paid them a visit?


As a parting thought: do today's tools will make code cohesion less important of a consideration? Right clicking to go to a definition, makes my life a heck of a lot easier in even badly written and organized code.


Related Reading

More Insights

Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.