Can the C# using statement be written without the curly braces?
Yes, you can also put them in one using statement:
using (MemoryStream data1 = new MemoryStream(),
data2 = new MemoryStream())
{
// do stuff
}
The same rules apply when you omit the curly braces in a for
or an if
statement.
Incidentally if you reflect into the compiled code, the compiler decompiler adds the braces.
Exactly what he said. The code above is exactly the same as writing:
using (MemoryStream data1 = new MemoryStream())
{
using (MemoryStream data2 = new MemoryStream())
{
// Lots of code
}
}
You can omit the curly braces after an if/else/for/while/using/etc statement as long as there is only one command within the statement. Examples:
// Equivalent!
if (x==6)
str = "x is 6";
if(x == 6) {
str = "x is 6";
}
// Equivalent!
for (int x = 0; x < 10; ++x) z.doStuff();
for (int x = 0; x < 10; ++x) {
z.doStuff();
}
// NOT Equivalent! (The first one ONLY wraps the p = "bob";!)
if (x == 5)
p = "bob";
z.doStuff();
if (x == 5) {
p = "bob";
z.doStuff();
}