Archive for category Extension Methods

C# Acrobatics : Lambdas and Expression Methods as a replacement for NVelocity

I’ve been very quiet recently. (I’m trying to not be so loud, Scott. 🙂 ) You see, I’ve been writing a lot of ASP.Net code for a site I’m working on. And, to be honest, I’ve been having a lot of trouble. The source code for .Net has been very helpful, and I’ve learnt a lot about what’s going on under the covers of ASP.Net because of it.

(Note: I won’t comment here on the quality of the code I’ve found – I’ll leave that up to you to judge. But in any case, I’ve been trying to build on top of it.)

One thing I’ve found to be important is the reliance on Web Controls. (It’s got something to do with javascript libraries, but that’s another story.) Getting away from the "standard" way to do ASP.Net isn’t easy though. Even the ninjas on the ASP.Net MVC team seem to be having trouble. However, with the magic of lambdas and extension methods in C#, I think I might have just about managed to get something usable. I thought I’d publish my work here, and see what comments I got.

I think it’s best to start with what my ASP.Net code looks like once I’ve got everything working. (Notice I still have some Web Controls in there, but that’s because I’ve not worked out how to do sorting of data without web controls yet.)

The inspiration for this was taken from the improvements made to NVelocity by the gurus on the Castle Project. I thought it looked great, and I’d like something similar, but I didn’t really want to learn a whole new scripting language and integrate it into my working environment just for rendering a bit of HTML. So I built some C# classes to do a similar thing for me instead. It’s not as nice as NVelocity, but it’s okay for now.

Warning: The following code may contain statements of a disturbing nature to more sensitive readers. We cannot be held responsible for any confusion, delusion or mental illness caused by this code.

It starts by taking a collection of Task objects, and calling the extension method "ForEach" on them:

<% Tasks.ForEach(sections => {
   sections.NoData = tasks => {
%>
   <p>
   Hey, you've got nothing to do.</p>
   <p>
<%
   };
   sections.BeforeAll = tasks => {
   %>
  <table class="task-list">
    <tr class="task-list-header">
      <th>
        <asp:LinkButton runat="server" CommandName="Sort" CommandArgument="StartDate"
          Text="Started" />
      </th>
      <th>
        <asp:LinkButton runat="server" CommandName="Sort" CommandArgument="DueOn"
          Text="Due" />
      </th>
      <th>
        <asp:LinkButton runat="server" CommandName="Sort" CommandArgument="Priority"
          Text="Priority" />
      </th>
      <th>
        <asp:LinkButton CssClass="task-description" CommandName="Sort" CommandArgument="Title"
          Text="Description" runat="server" />
      </th>
<th> </th> </tr> <% }; sections.Before = task => { %> <tr class="<%= this.tableCssClasses.Next() %>"> <% }; sections.Each = task => { %> <td> <div class='calendar calendar-icon-<%= task.StartMonth %>'> <div class="calendar-day"> <%= task.StartDayOfMonth %></div> </div> </td> <td> <div class='calendar calendar-icon-<%= task.DueMonth %>'> <div class="calendar-day"> <%= task.DueDayOfMonth %></div> </div> </td> <td> <%= task.Priority %> </td> <td class="task-title"> <a href='<%= Href.For("~/Tasks/{0}/Show.aspx", task.ID) %>'><%= task.Title %></a> </td> <td> <asp:Button ID="Button1" runat="server" CssClass="button" CommandName="Delete" Text="Mark Done" /> </td> <% }; sections.After = task => { %> </tr> <% }; sections.AfterAll = task => { %> </table> <% }; }); %>

It might take a while to grasp what’s going on here. The code actually starts using an Extension method to IEnumerable that looks like this:

public static void ForEach<T>(this IEnumerable<T> enumerable, ForeachSectionSetter<T> sectionSetter) {
  if (enumerable != null) {

    if (sectionSetter != null) {
      ForeachSections<T> sections = new ForeachSections<T>();
      sectionSetter(sections);

      if (enumerable.Count() == 0) {
        if (sections.NoData != null)
          sections.NoData(enumerable);
        return;
      }

      if (sections.BeforeAll != null)
        sections.BeforeAll(enumerable);

      int itemIndex = 0;
      T previousItem = default(T);

      foreach (T item in enumerable) {
        if (sections.Before != null)
          sections.Before(item);
        if (itemIndex % 2 == 1 && sections.Odd != null)
          sections.Odd(item);
        if (itemIndex % 2 == 0 && sections.Even != null)
          sections.Even(item);
        if (itemIndex > 0 && sections.Between != null)
          sections.Between(previousItem, item);
        if (sections.Each != null)
          sections.Each(item);
        if (sections.After != null)
          sections.After(item);
        itemIndex++;
        previousItem = item;
      }
      if (sections.AfterAll != null)
        sections.AfterAll(enumerable);
    }
  }
}

The delegate ForEachSectionSetter is used by the calling method with a lambda expression. As a parameter it receives an ForeachSections object, which looks like this:

public class ForeachSections<T> {
  public Action<T> Each { get; set; }
  public Action<IEnumerable<T>> BeforeAll { get; set; }
  public Action<T> Before { get; set; }
  public Action<T,T> Between { get; set; }
  public Action<T> Odd { get; set; }
  public Action<T> Even { get; set; }
  public Action<T> After { get; set; }
  public Action<IEnumerable<T>> AfterAll { get; set; }
  public Action<IEnumerable<T>> NoData { get; set; }
}

The calling method gets the chance to set the properties of this class before it is returned to the constructor of the ForEach method for processing. And because each property is already preset to a default value (Null in this case), the constructor can use the ForeachSections object just like a set of default or optional parameters. The caller can simply set values to the properties it needs, and ignore the rest.

If I had tried this another way, using overloadable constructors, it would have led to multiple constructors with indistinguishable signatures. If I’d have used property initializers, I wouldn’t have been able to run the whole routine without requiring a second call to the object, which actually wasn’t possible.

Basically, I couldn’t think of another way to do it.

The properties of the ForeachSections object are all delegates too. That means that we can use them with lambdas, which gives us lambdas inside of a lambda. (Hmm, very confusing!)

So what do you think? Could you use something like this? Can you make it simpler? Leave me a comment if you can.

, , , , ,

No Comments

Design Guidelines for LINQ

Have you wondered if and when you should use the new LINQ features in .Net 3.5?

Like, where should I put a new extension method? Should I use Func<T> or a custom delegate? How do I best implement a mix-in (extension methods on an interface)?

Well, Mircea Trofin has just published a new draft of some LINQ design guidelines. You might just find your answers there.

, ,

No Comments

Can You Pass an Anonymous Type Across Functions?

One of the biggest questions with Anonymous Types is “can I pass them around?” If not, why not? Can you do something like this, for example:

var GetAnonymousValue() {
  return new { Name = "Richard Bushnell" };
}

void Main() {
  var value = GetAnonymousValue();
  var name = value.Name;
}

The answer is simple: no, you can’t pass anonymous types across functions. var is not a dynamic variable, like in JavaScript. The CLR knows nothing about “var”, as the compiler just uses it to infer types when a variable is initialized.

At least, that was the answer until now. Using a simple extension method and generics, Alex James just showed a nice way to pass them around on his blog.

The trick is to use an example of the anonymous type you expect.

object GetAnonymousValue() {
  return new { Name = "Richard Bushnell" };
}

void Main() {
  var value = GetAnonymousValue().CastByExample(new { Name = "" });
  var name = value.Name;
}

While this might be a little dangerous, especially if you’re not testing your code regularly, this could be the solution to a few problems I can already think of.

Watch out for casting exceptions at runtime though! If you make a mistake anywhere, you’ll won’t get a compile-time exception, but a nasty runtime exception instead.

No Comments

Fun with C# Extension Methods: Quick Loops

In my last post, I demonstrated an extension method for easy creation of ranges, using the 1.To(x) syntax, similar to the Ruby [1..x] syntax. Today I’m writing another copy of a Ruby idea which lets you do a quick loop using a terse and easy-to-read syntax.

Remember, if you want to create your own extension methods, you need to define a static class to put them in, like this:

public static class Extensions

Quick Loops

Rails is king of easy loops. You can write this:

  3.times do { // block of statements }

Why not do the same in C# 3.0? It’s easy. Add this to your extensions class:

public static void Times(this int repeatCount, Action<int> action)
{
  for (int i = 1; i <= repeatCount; i++)
  {
    action(i);
  }
}

Now you can use this syntax in your program:

100.Times(t =>
{
  Console.WriteLine("t:{0}", t);
});

t references the current counter position from 0 to the specified number.

Question: Which would be clearer to you if you were taking over someone else’s code – the for loop in the extension method, or the .Times syntax?

It might be unfamiliar to me at first, but once I’d gotten the hang of it, I would find the extension method syntax to be much easier to follow in most situations.

“Hey, Richard”, I hear you shout. “What if a variable were used, such as the number of rows? Would it still be clear?” Hmm, maybe not, methinks.

A quick example:

table1.Rows.Count.Times(t =>
{
  Console.WriteLine("t:{0}, name:{1}", t, table1.Rows[t]["Name"]);
});

With bad variable naming, this could get unwieldy. But with good naming it still looks okay:

var noOfRows = table.Rows.Count;
noOfRows.Times(rowNo =>
{
  var row = table.Rows[rowNo];
  Console.WriteLine("rowNo:{0}, Name:{1}", rowNo, row["Name"]);
});

This would be opposed to the more usual:

for (int rowNo = 0; rowNo < table.Rows.Count; rowNo++)
{
  var row = table.Rows[rowNo];
  Console.WriteLine("rowNo:{0}, Name:{1}", rowNo, row["Name"]);
}

or even:

foreach (DataRow row in table.Rows)
{
  var rowNo = row.Table.Rows.IndexOf(row);
  Console.WriteLine("rowNo:{0}, Name:{1}", rowNo, row["Name"]);
}

Despite the long syntax of the for loop, and the backwards somersaults you need to do to get the row index in the for loop, with the Times syntax you still have to use a lamda expression, and mustn’t forget the semicolon at the end of the lamda expression block. With the usual loops you don’t. As with all things, you wouldn’t always use this syntax, but sometimes it would be a good alternative.

What’s next?

Ruby is full of neat little tricks like I’ve presented here, and personally, I love ’em. I’ll write some more soon, including “inject”, “collect” and “each”.

No Comments

Fun with C# Extension Methods: Easy Ranges

I’m not a real Ruby on Rails developer, but I’ve tried to learn it, just to broaden my perspective. Coming from a C# background, I’m impressed by how easy it is to read Ruby code. In fact, it is usually so compact and self-descriptive, you can understand it just by reading the code. Imagine not having to write comments because your code is so clear! That’s what you can do with Ruby.

And now, using extension methods, it’s almost as easy to write C# code which is just as self-descriptive as Ruby code. I’m going to try to demonstrate that in this post.

Before we start, if you want to create your own extension methods, you need to define a static class to put them in:

public static class Extensions

I generally make my extension methods public, because I intend them to be usable for all my projects. I’m putting them all in a common project which I reference in most of my work.

Easy Ranges

.Net 3.5 includes a new extension method for IEnumerable<int> called Range. Its first parameter is the starting integer, and its second is the number of integers to count. So to get a range from 1 to 10, you write:

Enumerable.Range(1, 11)

It might be just me, but personally, I find that syntax a bit counter-intuitive. If I want the range 100 to 200, I’d have to write:

Enumerable.Range(100, 101);

Could I read that later, and easily understand what was being done? Not without a comment or two. When I read that code, it’s not obvious at all what range is being used.

But, let’s not complain. It’s easy to implement our own interpretation and extend an integer with a new method. Let’s make it more Ruby-like.

In Ruby you declare a range from 1 to 10 like this: [1..10]. A range of 100 to 200 looks like this: [100..200]. That’s nice, but pretty much impossible for us to define for C#. I think it would be just as good though if I could write something like this in my programs:

IEnumerable<int> range = 1.To(3);

For me, that compares quite nicely to the Ruby syntax. Plus, I get intellisense for the method on an integer, so it works well.

To implement that, I just have to define a new extension method like so:

public static IEnumerable<int> To(this int first, int last)
{
  return Enumerable.Range(first, last - first + 1);
}

Using this new method and the new C# LINQ syntax, I could select all even numbers from 1000 to 2000 like this:

var odds = from i in 1000.To(2000)
           where i % 2 == 0
           select i;

foreach (var i in odds)
  Console.WriteLine(i);

This gives 501 items, as you’d expect.

What’s next?

Ruby has a nice little syntax for defining a quick loop. Rails uses it a lot. I’m going to demonstrate how to create the same syntax in C# in my next post.

2 Comments

A Mixin for IComparable

Following on from my other posts on C# Mixins, here’s a short one to demonstrate the benefits of Mixins using IComparable<T>.

I don’t know about you, but I can never remember how the CompareTo method of IComparable<T> works. If I remember correctly, it gives back -1 if the value of the compared object is less than the value of the called object, and +1 if the compared object is greater than the value of the called object.

No, wait! That’s the wrong way round! See what I mean?

The CompareTo method is defined like this:

int CompareTo(T other)

According to the MSDN Library, the value it returns is:

Value Meaning
Less than zero This object is less than the other parameter.
Zero This object is equal to other.
Greater than zero This object is greater than other.

Now I don’t know about you, but I always have trouble with that. Mix-ins to the rescue!

What I really need is to define my own methods on the IComparable<T> interface. Something like LessThan, MoreThan and ValueEquals. That would be much more valuable. I could define those methods in a superclass, and have my new classes all inherit from that superclass. But that would bind me to a certain structure, reduce the coherency of my classes, and make me feel bad. But if I implement IComparable<T> with its sole method, I can use a Mixin to take advantage of that method and add the new functionality I need, without affecting the structure of my code.

Here’s an example using the Temperature class shamelessly lifted from the MSDN Library.

The class Temperature is defined as:

public class Temperature : IComparable<Temperature>
{
  // Implement the CompareTo method. For the parameter type, Use
  // the type specified for the type parameter of the generic
  // IComparable interface.
  //
  public int CompareTo(Temperature other)
  {
    // The temperature comparison depends on the comparison of the
    // the underlying Double values. Because the CompareTo method is
    // strongly typed, it is not necessary to test for the correct
    // object type.
    return m_value.CompareTo(other.m_value);
  }

  // The underlying temperature value.
  protected double m_value = 0.0;

  public Temperature(double degreesKelvin)
  {
    this.Kelvin = degreesKelvin;
  }
}

Note that Temperature implements IComparable<Temperature>.

So now if you define a static extension class for IComparable<T>, you should also be able to use it with IComparable<Temperature>.

Here are the extension methods I’m going to add – LessThan, MoreThan, and ValueEquals:

public static class IComparableExtensions
{
  public static bool LessThan<T>(this IComparable<T> comparable, T other)
  {
    return comparable.CompareTo(other) < 0;
  }

  public static bool MoreThan<T>(this IComparable<T> comparable, T other)
  {
    return comparable.CompareTo(other) > 0;
  }

  public static bool ValueEquals<T>(this IComparable<T> comparable, T other)
  {
    return comparable.CompareTo(other) == 0;
  }
}

My program now references the IComparableExtensions class by importing its namespace. I then write:

var t1 = new Temperature(273);
var t2 = new Temperature(100);

All I had to do was implement IComparable<T> with its one CompareTo method (which was trivial), and I automatically get the extension methods LessThan, MoreThan and ValueEquals mixed-in to my Temperature class.

if (t1.LessThan(t2))
  Console.WriteLine("t1 is less than t2");
else if (t1.MoreThan(t2))
  Console.WriteLine("t1 is more than t2");

And this doesn’t just work with IComparable<Temperature>, it works with anything which implements IComparable<T>. Classes implementing IComparable<int> would also get access to the new methods, for example.

Here’s the output of the code:

t1 is more than t2

… as you would expect.

And voila! That’s why mix-ins can be so useful.

I’ve intentionally done this example using a well-known interface, to make it easier to understand. But imagine what you could do by inheriting from a particular class of your own, defining your own interface, and then adding in more functionality using a mixin. You’ve nearly got multiple inheritance.

More to come on this…

No Comments

A not-so-simple Mixin with C# 3.0

My last post gave a simple idea of how to do a Mixin with C#. Rather than repeating what someone else has already done, if you want to see a more complex example of what can be done, check out Create Mixins with Interfaces and Extension Methods by Bill Wagner at MSDN.com.

No Comments