Sunday, August 31, 2008

Auckland Codecamp 2008

Links and resources from Codecamp:

Thursday, August 14, 2008

Viewstate and the C# ?? null-coalescing operator

The ?? (null coalescing) operator is a handy way to check whether a value is null, and if so return an alternate value.

I find it particularly useful in combination with viewstate for putting terse properties on user controls with default values.

E.g.
/// 
/// A Property that defaults to false unless set otherwise.
/// 
public bool SomeProperty
{
  get { return ViewState["viewstateKey"] as bool? ?? false; }
  set { ViewState["viewstateKey"] = new bool?(value); }
}

See Also: Scott Gu - The C# ?? null coalescing operator (and using it with LINQ)

Wednesday, August 13, 2008

Microsoft .NET Framework 2.0 - Application Development Foundation - Multicast Delegate

During my study for the 70-536 exam I came across a blog page with some questions from the exam. One of which is about multicast delegates:
Q. You need to write a multicast delegate that accepts a DateTime argument and returns a Boolean value. Which code segment should you use?
  1. public delegate int PowerDeviceOn(bool, DateTime);
  2. public delegate bool PowerDeviceOn(Object, EventErgs);
  3. public delegate void PowerDeviceOn(DateTime);
  4. public delegate bool PowerDeviceOn(DateTime);
The first observation I'd make about the available answers it that they are all missing the parameter names. They may also be missing ref and/or out keywords. Who knows. I'll assume that only the parameter names are missing.

Looking past that, I've seen comments floating round the web that "Multicast delegates must contain only methods that return void". This is misleading. It's quite possible to have a return value. See the MSDN article Multicast Delegate Internals, particularly the "Method Returns and Pass-By-Reference" section towards the end.

The issue identified in the above article is that if the "subscribers return a value, it is ambiguous which subscriber’s return value would be used". In cases such as this where the return value from each invoked method is of interest the MulticastDelegate.GetInvocationList() method can be used to manually enumerate through the list of subscribers and call them individually.

While it is possible to have return types other than void I'd be wary of doing so in practice unless there was a compelling reason.