Often, while investigating some code I’m developing, I’ll throw in a Console.WriteLine here or there too see a value when the program is run. The drawback to Console.WriteLine is that I have to wrap an expression in parenthesis and possibly break it apart. For example given this expression:
a().b().c();
let’s suppose I want to print the value of b(). I’ll have to do something like:
var val = a().b();
Console.WriteLine(val);
val.c();
That’s alot of editing just to see a value.
My solution has been to use this extension method:
public static T Disp<T>(this T obj)
{
Console.WriteLine(obj);
return obj;
}
I can inject a call to Disp in any method chain without altering the value of the overall expression. To see the result of b() in the above example, I’d do:
a.().b().Disp().c()
My question is, is there already some method like Disp in .NET? Is there a better way to implement Disp? Are there drawbacks to this technique?
update 2012-02-09
I also added an overloaded version which accepts a format string:
public static T Disp<T>(this T obj, string format)
{
Console.WriteLine(string.Format(format, obj));
return obj;
}
I don’t see a problem with it, although you might consider making it more general with an
Action<T>parameter:This is similar to Tap in Ruby.
Instead of your
Dumpmethod you can then do: