5

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?

Community
  • 1
  • 1
Arion
  • 31,011
  • 10
  • 70
  • 88
  • It it really much better to write that instead of `sb.Append("foo")`?? I'm programming for 12 years in VB.NET and have never understood the benefit of the with statement. Just another thing you must lookup everytime(What was that again?) – Tim Schmelter Feb 28 '12 at 13:36
  • @TimSchmelter: I wonder the same thing. I code in VB.NET for the last 4 years maybe, and have never found a use for the With statement, except for the New...With construct. – Meta-Knight Feb 28 '12 at 13:44

5 Answers5

13

No, there isn't.

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

Blog post from Scott Wiltamuth, Group Program Manager for Visual C#, about the with keyword: https://web.archive.org/web/20111217005440/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");
snipsnipsnip
  • 2,268
  • 2
  • 33
  • 34
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • 4
    Just out of curiosity, could you provide an example about a confusing VB.Net code that uses With/End With? – ken2k Feb 28 '12 at 13:33
  • you might also note that C# has the object initializer syntax, but it can only be used to set public instance variables, not make function calls. – Scott M. Feb 28 '12 at 13:53
4

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.

Justin
  • 6,611
  • 3
  • 36
  • 57
2

No, there is no equivalent syntax.

With is VB/VB.NET only.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
2

There is an equivalent for New Type With:

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

, but not for the common With.

Anders Marzi Tornblad
  • 18,896
  • 9
  • 51
  • 66
0

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.

dice
  • 2,820
  • 1
  • 23
  • 34