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:
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:
- 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.
- 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.
- 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…