Why doesn't C# have a 'with' statement?
Pascal, VB and some other languages make it easier to perform multiple operations on an object by providing "with statement" support. For example, this VB code:
With Button1
.Text = "Hello"
.BackColor = Color.Blue
End With
uses a "with statement" to set the Text and BackColor properties of a button. The above code is equivalent to
Button1.Text = "Hello"
Button1.BackColor = Color.Blue
Complex expressions can be used in with statements, e.g.,
With MyDataStructure.GetButton(44)
.Text = "Hello"
.BackColor = Color.Blue
End With
In such situations, there can be a performance benefit over the equivalent in-line code that duplicates the complex sub-expression:
MyDataStructure.GetButton(44).Text = "Hello"
MyDataStructure.GetButton(44).BackColor = Color.Blue
However, there is equivalent in-line code that is just as performant:
Dim b as Button = MyDataStructure.GetButton(44)
b.Text = "Hello"
b.BackColor = Color.Blue
So that's what "with statements" are all about. Now I can address the original question, which is "Why doesn't C# have a with statement?" There are several reasons:
- Small or non-existent readability benefits. We thought the readability benefits were small or non-existent. I won't go as far as to say that the with statement makes code less readable, but some people probably would.
- Increased language complexity. Adding a with statement would make the language more complex. For example, VB had to add new language syntax to address the potential ambiguity between a local variable (Text) and a property on the "with" target (.Text). Other ways of solving this problem also introduce language complexity. Another approach is to push a scope and make the property hide the local variable, but then there's no way to refer to the local without adding some escape syntax.
- C++ heritage. C++ has never had a with statement, and the lack of such a statement is not generally thought to be a problem by C++ developers. Also, we didn't feel that other changes -- changes in the kind of code people are writing, changes in the platform, other changes in the language, etc. -- made with statements more necessary.
We're open-minded about these things, though. The aim of this "Ask a language designer" forum is to explain some of our design choices and get feedback on them. If you think there's a good argument for adding with statement support, please send me mail and describe why with statements are important to you and how you would use them.
Scott Wiltamuth, Group Program Manager for Visual C#
Discuss this in C# Language Forum.