Extension methods and a plea for mixins


I was having a spot of trouble the other day trying to get my extension methods to show up in my ASP.NET MVC Views.  One of the issues we’ve run into is trying to make our Views (more) intelligent on the HTML they create.  Our Views still only work off of a Model, but they can be much more intelligent on creating the HTML for a single property, or group of properties.  However, if we’re trying to extend our Views (and not that crazy HtmlHelper), there are at least 6 View types we have to deal with:

  • ViewUserControl
  • ViewUserControl
  • ViewPage
  • ViewPage
  • ViewMasterPage
  • ViewMasterPage

Now, at least the generic types inherit from their counterpart (ViewPage inherits ViewPage).  However, no real correlation exists between the six types, other than IViewDataContainer for the most part (which the ViewMasterPages do NOT implement).  We noticed quite a bit of duplication in our common base behavior for each of these types.  Since we couldn’t make all of these inherit from the same type, making extension methods off of a common interface seemed to make sense:

public static class ViewBaseExtensions
{
    public static string HtmlFor<TModel>(this IViewBase view, 
        Expression<Func<TModel, object>> modelExpression)
    {
        // Zomething interesting
    }
}

Since I was working in the View, I expected my HtmlFor method to show up as an extension method.  Even after some helpful tweets from folks, nothing seemed to work; my extension methods simply did not show up.  What was my problem?  Here’s a simplified example:

public static class FooExtensions
{
    public static void Bar(this Foo foo)
    {
    }
}

public class Foo
{
    public void PrettyPlease()
    {
        Bar(); // Does not compile
        this.Bar(); // Not so magic :(
    }
}

I defined an extension method for the Foo type, but tried to use it inside Foo.  Well, that doesn’t work unless I call the extension method directly on an instance of Foo, which leads me to use the “this” keyword.  Which is why you see examples like these that make prodigious use of the “this” keyword.

Duplication be damned, all that “this” nonsense just isn’t worth it.  Especially when you realize that it’s only there to initiate the extension method compiler magic.

In the end, this is just another example that extension methods aren’t mixins, and I seriously doubt the new C# 4.0 “dynamic” keyword will do the trick.  I’m starting to believe that if I want a dynamic language, I should stop looking for a static language to bend yoga-style backwards to be one.

Ten things to retire in 2009