Dan Byström’s Bwain

Blog without an interesting name

With Zwei.Drei.Vier.Links()

Posted by Dan Byström on December 1, 2004

In preparation for a continued discussion of how a language could assist us in checking for null references, I’ll state what I see as drawbacks with the With-statement in VB (or Pascal for that matter, where it has its origin). Eh, say that again? Well, it’ll become clear later on.

In VB6 I used With a lot. In the world of COM it was not merely a convenience, but also an optimization technique, since the programs ran faster when calls to AddRef/ReleaseRef were reduced. In .NET that’s not an issue anymore.

Anyway I still miss it in C#.

Consider the following piece of VB code:

With Customer(42)
  With .Order(3)
    .Lock()
    Process .Order(3)
    Customer(42).Update
    .Unlock()
  End With
End With

Never mind the object names or why you’d like to do exactly something like this. I’m only interested in the implications made by the With statements. We can observe that:

  1. We can only have one “active” With at a time, so nesting them won’t help us access the outer With. Nested Withs also makes the code hard to read.
  2. If we have the need to pass the “withed” (I don’t have a better name) object down to a method (like the Process method in the example above) we have to reevaluate the “withed” object.
  3. Entering a With block with a null/Nothing reference is completely and utterly useless, yet it is allowed, and the exception won’t occur until we try to access the first method/property of the “withed” object.

Given those drawbacks, it may be understandable that the With statement wasn’t made part of the C# language. I think 1) and 2) are quite obvious, but 3) is more my own personal reflection and something I want to improve upon!

What if we could overcome all three issues? Stay tuned…

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

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

 
%d bloggers like this: