Will.Whim

A weblog by Will Fitzgerald

C# Lambdas are almost like C# compile-time macros

I was writing some instrumentation code in C# today that looked like this:

MeasureOn("SomeFeature");
ComputeSomeFeature();
MeasureOff("SomeFeature");
MeasureOn("AnotherFeature");
ComputeAnotherFeature();
MeasureOff("AnotherFeature");

If I were using a language with (compile-time) code macros (like Clojure, Scheme or Lisp), I’d prefer to write something like:

Measuring("SomeFeature"){ComputeSomeFeature();}
Measuring("AnotherFeature"){ComputeAnotherFeature();}

But C# doesn’t have such a basic and useful thing, by design (bad design, I think, but still by design).

But C# does have first-class anonymous functions, so it’s possible to write methods that take one of these as a parameter. This allowed me to write something like:

Measuring("SomeFeature", () => { ComputeSomeFeature(); });
Measuring("AnotherFeature", () => { ComputeAnotherFeature(); });

This is almost not horrible. It was a little tricky to find out how to declare anonymous functions in C# code. But it runs out that .NET has a special class for anonymous functions which take no values and return no values; .NET calls one of these an Action.

So, my Measuring method looks something like this:

private void Measuring(string feature, Action f)
{
  MeasureOn(feature);
  f();
  MeasureOff(feature);
}

I did some simple timing on the ‘macro’ vs. the ‘non-macro’ version of these; basically, you pay the cost of an additional function call. I don’t know enough about .NET to know how much continuation state would get passed; this was adequate for my purposes, anyway. Perhaps a more knowledgeable commentator will comment.

(This is a note to my future self; I’m sure to forget the details about getting around the limits of C# not having compile-time macros).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: