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));
Advertisements

Responses

  1. 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 Reply

Please log in using one of these methods to post your comment:

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

Categories

%d bloggers like this: