Coalescing delegates

Did you know the coalesce operator (??) works for delegates? I had never really thought about it, but it does and you can use it to create confusing passages of code like this one… :)

delegate String ConvertToString(LookupEntity entity);
String defaultStringConversion(LookupEntity entity) { return "default"; }

String loadAndDisplay(Guid id, ConvertToString converter) {
  LookupEntity entity = db.LoadEntity(id);
  return (converter ?? defaultStringConversion)(entity);
}

[Test]
public void TestLoadAndDisplay() {
  Guid id = Guid.Empty;
  ConvertToString customConversion = delegate { return "custom"; };
  Assert.That(loadAndDisplay(id, defaultStringConversion), Is.EqualTo("default"));
  Assert.That(loadAndDisplay(id, customConversion), Is.EqualTo("custom"));
  Assert.That(loadAndDisplay(id, null), Is.EqualTo("default"));
}

In this contrived example we are using it to provide a default delegate function if none is specified in the call to loadAndDisplay. I’m not necessarily recommending this, I just found it interesting :)

Comments