Thursday, September 23, 2010

VB + C# Adventures (Part 4)

Event Handlers

Adding and removing event handlers in VB is pretty straightforward.  I think the syntax, although wordy, lends itself to readability better than its C# counterpart.  In VB for example:

...
AddHandler o.SomeEvent, AddressOf Handler
...
RemoveHandler o.SomeEvent, AddressOf Handler

In C#, you’d have to do the following:

...
o.SomeEvent += new EventHandler(Handler);
...
o.SomeEvent -= new EventHandler(Handler);

Now the thing that struck me as “funny” was the need to create a new EventHandler delegate (or whatever event handler delegate you created) to remove it in the C# syntax…

 

Method Parameters Passed By Reference

Since I’m using methods that pass parameters as reference, you have to use the ref identifier before those parameters in C#.  At first this bugged me because I was so used to not having to do it in VB.  But is it necessarily better not having to identify a reference parameter?  I got to thinking about this and I now think it’s good to have to denote it. 

Why do I think so now?  The intent of a parameter passed by reference is to change the parameter itself (of course this has different implications for value types versus reference types).  This can lead to confusion if you don’t know that the variable that you’re passing in can change.  Requiring the ref identifier alleviates this confusion in my opinion.

No comments: