Question

Possible Duplicate: Equivalence of “With…End With” in C#?

So I don't know if this question has been asked before and I am not a big fan of VB.NET. But one syntax that I am missing in C# is the With syntax.

In VB.NET you can write:

Dim sb As New StringBuilder
With sb
    .Append("foo")
    .Append("bar")
    .Append("zap")
End With

Is there a syntax in C# that I have missed that does the same thing?

Was it helpful?

Solution

No, there isn't.

This was intentionally left out of C#, as it doesn't add much convenience, and because it can easilty be used to write confusing code.

Blog post from Scott Wiltamuth, Group Program Manager for Visual C#, about the with keyword: http://msdn.microsoft.com/en-us/vstudio/aa336816.aspx

For the special case of a StringBuilder, you can chain the calls:

StringBuilder sb = new StringBuilder()
  .Append("foo")
  .Append("bar")
  .Append("zap");

OTHER TIPS

There is no direct analogue to the VB With statement.

However, note that StringBuilder.Append returns the StringBuilder instance, so the following code is equivalent to your original:

sb.Append("foo").Append("bar").Append("zap");

or even

sb.Append("foo")
  .Append("bar")
  .Append("zap");

This is not possible for all objects/methods, though.

No, there is no equivalent syntax.

With is VB/VB.NET only.

There is an equivalent for New Type With:

var obj = new Type {
    PropName = Value,
    PropName = Value
};

, but not for the common With.

There isn't - this is Visual Basic-only.

One of the prime reasons it was left out of C# was that it can lead to confusing code, for example when using nested With statements.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top