Posted by: leppie | August 23, 2007

Interesting C# construct

It’s been a while since I have seen some weird looking C#, but I just came up with this one:

class Foo
{
  CallTargetWithContext0 target0;
  CallTargetWithContext1 target1;
  CallTargetWithContext2 target2;
  CallTargetWithContext3 target3;
  CallTargetWithContext4 target4;
  CallTargetWithContext5 target5;
  CallTargetWithContextN targetN;

  public Foo(Delegate target)
  {
    target =
    ((Delegate)(target0 = target as CallTargetWithContext0)) ??
    ((Delegate)(target1 = target as CallTargetWithContext1)) ??
    ((Delegate)(target2 = target as CallTargetWithContext2)) ??
    ((Delegate)(target3 = target as CallTargetWithContext3)) ??
    ((Delegate)(target4 = target as CallTargetWithContext4)) ??
    ((Delegate)(target5 = target as CallTargetWithContext5)) ??
    ((Delegate)(targetN = target as CallTargetWithContextN));
  }
}

Edit: This seems to work too, excluding the last cast gives you an error (which does not seem to make sense)

target =
(target0 = target as CallTargetWithContext0) ??
(target1 = target as CallTargetWithContext1) ??
(target2 = target as CallTargetWithContext2) ??
(target3 = target as CallTargetWithContext3) ??
(target4 = target as CallTargetWithContext4) ??
(target5 = target as CallTargetWithContext5) ??
((Delegate)(targetN = target as CallTargetWithContextN));

Responses

Ah the null coalescing operator, good stuff and it was new in C#2.0
more info here:
http://blog.devstone.com/aaron/archive/2006/01/02/1404.aspx

Leave a response

Your response:

Categories