Friday, September 5, 2003

Delegate -= Bugaboos

Mark Taparauskus is the author of DevelopMentor’s Programming C# course. As you might expect of someone with those credentials, he knows a lot about C#. He’s been making a habit recently of posting interesting little tidbits he finds to one of the internal mailing lists. This one concerns the use of the “-“ and “-=” operators on delegates. You may have see this usage before, as in:

delegate void Blah(int i, string s);
Blah b1 = new Blah(Foo.Bar);
Blah b2 = new Blah(Foo.Quux);

Blah b3 = b1 + b2;    // Chain two delegates together: b3 = (b1 b2)
Blah b4 = b3 - b1;    // Remove b1 from the chain: b4 = (b2)

As Mark has no homepage or blog (yet), he’s given me permission to repost his findings here:

Here are two random facts about op- and op-= with delegates that I think are interesting.

 

1. The *last* occurrence is removed:

(a b a) - (a) = (a b)

 

2. The right hand side has to be a contiguous sublist of the left side or nothing happens. A contiguous sublist just means the same elements in the same order.

 

So this one works as expected:

(a b c d) - (b c) = (a d)

 

But nothing gets removed here:

(a b c d) - (a c) = (a b c d)

 

No comments:

Post a Comment