jump to navigation

Tapping with C#3.0 February 6, 2008

Posted by James Webster in : development, dotnet , trackback

InfoQ have an article up about Ruby 1.9’s new ‘tap’ method. A little similar in concept to Unix’s ‘tee’ command it allows Rubyists to inject an arbitrary block of code into a method call chain in order to inspect or mutate the variable. Its useful in debugging apparently.

Hmmm… should be easy enough to replicate that in C#3.0. First we need an extension method on any type…

public static T Tap<T>(this T objectToTap, Action<T> tapAction) {
    tapAction(objectToTap);
    return objectToTap;
}

In usage…

StringBuilder buf = new StringBuilder("A good candidate because it's methods chain.");
buf.Append("One. ").Append("Two. ")
  .Tap((x) => Console.WriteLine("Tapping! " + x.ToString()))
  .Append("Three. ").Append("Four. ");
Console.WriteLine("Not tapping! " + buf.ToString());

Which results in console output…

Tapping! A good candidate because it's methods chain. One. Two.
Not tapping! A good candidate because it's methods chain. One. Two. Three. Four.

What do you think? Potentially useful or a gross violation of the Law of Demeter?

Comments»

no comments yet - be the first?