1

This is a really simple question but one I would like to know before moving forward so I understand the process.

In the tutorial I am following I was using an if statement. If you do the code below you don't need to use {}

if (userValue == "1")
    message = "You won a new car!"; 

But if you use more than one line of code you do need {}.

if (userValue == "1")
{
    WriteLine ("You won a new car!");
    ReadLine ();
}

Can someone explain to me in very simple terms why this is the case? I just need a rule of thumb so I can understand why. Nothing overly complicated I'm just a beginner. I understand that they identify a block of code but am not sure why this makes a difference between one or two lines?

Danrex
  • 1,657
  • 4
  • 31
  • 44
  • using braces even for single lines prevents accidentally flawed logic. This question has been asked many times already.... http://stackoverflow.com/questions/12193170/whats-the-purpose-of-using-for-a-single-line Muppet upvote ahoy! – Mitch Wheat Jan 11 '14 at 01:39
  • 1
    http://msdn.microsoft.com/en-us/library/fh88ctk1.aspx – OldProgrammer Jan 11 '14 at 01:39
  • @OldProgrammer - despite being link to C spec it is fine as C/C++/Java/JavaScript/C# have essentially the same rule for `if-statement`. – Alexei Levenkov Jan 11 '14 at 01:47
  • You are originally a Python programmer, aren't you? :) – Liel Jan 11 '14 at 03:59

10 Answers10

7

These are known as blocks.

A block permits multiple statements to be written in contexts where a single statement is allowed.

They are used to group one or more statements together. In control structures like if statements, they are used to make all the statements within the block conditional, rather than just the statement immediately following the if statement.

Blocks also have their own scope, meaning a variable defined within a block cannot be referenced outside the block, and two variables in separate blocks are distinct, even if they have the same name.

Most programming languages have blocks of some sort, and the fact that C# uses curly braces to delimit them places it in a family of syntactically related languages known as curly-brace languages, along with C, C++, Java, and many more.

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
5

In your example {} specifies a block of code. You can easily write the first one as

if (userValue == "1")
{
    message = "You won a new car!"; 
}

Sometimes you can omit the {} when block contains only one statement.

if (userValue == "1")
    message = "You won a new car!"; 

However, most people consider using brackets even when they can be omitted as a good coding practice, because skipping them can lead to some errors. To make it a little bit clear consider following code

if (userValue == "1")
    message = "You won a new car!"; 
    ReadLine();

It's equivalent to

if (userValue == "1")
{
    message = "You won a new car!"; 
}
ReadLine();

what makes ReadLine execute every time, no matter userValue value. That may be not what developer thought.

MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
4

But if you use more than one line of code you do need {}.

This is not strictly true. It's more accurate to so that if you have more than one statement then you need to use {}, not more than one line. Here is a quick example which has many lines but needs no {}

if (...)  
  try {
    Method();
  } catch { 
    ...
  }

In this example the item following the if line has many lines but requires no braces. This is because the try construct itself constitutes a single statement. When there are multiple statements which need to be executed as a part of the if then you use {} to group them. Even though a {} can contain multiple statements, the {} construct itself counts as a single statement.

There are two notable exceptions to this rule though: labels and declarations. Both are statements but neither can be used directly after an if (...) statement.

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
3

The {} indicates a block of code. If you have more than one statement that you want to be performed if the if is true, then you need to use these.

Example: Without the {} this block:

if (userValue == "1")
   WriteLine ("You won a new car!");
   ReadLine ();

Would perform the ReadLine() command whether or not the userValue is equal to 1.

Contrast that with the one with curly braces:

if (userValue == "1")
{
    WriteLine ("You won a new car!");
    ReadLine ();
}

Now in case the userValue is not equal to 1, both command inside the curly braces are skipped and the execution continues with the next statement after the } sign.

Martin Zikmund
  • 38,440
  • 7
  • 70
  • 91
1

{} defines the scope of an expression. In c# and a couple other languages they've made it possible to shorthand that for simple expressions, like your first example.

1

{} defines execution Scope in C based languages, such as C++, C#, Java. If you add {} to the if statement, you define what is going to be executed inside of that condition.

//1.both lines are surrounded by { }
if (userValue == "1")
{
   //executes both lines when value is 1
   WriteLine ("You won a new car!");
   ReadLine ();
}

//2.No { } after the if statement
if (userValue == "1")
   //executes only this one when value is 1 - it's scope is implied (see point 3.below)
    WriteLine ("You won a new car!");
 //this one always will get executed, as it is not in scope of the if statement 
 ReadLine ();

 //3 - no {} means implied scope for one liner
 if (userValue == "1")
    message = "You won a new car!"; 

 //and is equivalent to 
 if (userValue == "1")
 {
     message = "You won a new car!"; 
 }
denis morozov
  • 6,236
  • 3
  • 30
  • 45
1

Your first example is C#'s way of providing a shortcut. The compiler treats

if (userValue == "1")
     message = "You won a new car!";

and

if (userValue == "1") 
{
    message = "You won a new car!";  
}

as being exactly the same.

It comes down to personal preference whether to use the shorthand for one-liners;

A common example is a quick return from a function:

if (isValid = false)
    return false;

There's no right or wrong way to do it of course, but a personal pet peeve I have is when people do this:

if (userValue == "1")
    message = "You won a new car!";  
else
    message = "You won a hippopotamus!"

This is bad form (in my humble opinion) even though it will compile.

The important thing is, whichever way you decide to write your one-liners, be consistent with one way or the other throughout your code.

Dmitriy Khaykin
  • 5,238
  • 1
  • 20
  • 32
1

There's no difference between:

if (userValue == "1")
    message = "You won a new car!"; 

and

if (userValue == "1")
{
    message = "You won a new car!"; 
}

...other than style. But:

if (userValue == "1")
    message = "You won a new car!"; 
    GiveNewCar();

Now, you're out of cash, because everyone's getting a new car. Without the scoping block, only the statement immediately following the if conditional will be tied to/protected by the if statement. Lines following won't be. To prevent this, you want:

if (userValue == "1")
{
    message = "You won a new car!"; 
    GiveNewCar();
}

Now, only those deserved few will get one.

This is why people often recommend always including the scoping parentheses, even if they're not strictly needed - to prevent bugs when the second line of code is added, and all of a sudden your customer's driveways fill up with Fords.

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
1

Imagine if you had

if (userValue == "1")
    WriteLine ("You won a new car!");
    ReadLine ();

In c# (and most languages) indentation doesnt make any difference (aka 'whitespace')

As far as C# is concerned thats the same as

if (userValue == "1")
    WriteLine ("You won a new car!");
ReadLine ();

Which is not what you intended! Hence you need the { }. The single line works because the compiler can see the semi-colon on the end

If you are interested in languages where {} are not used and indentation is used
    look at python
pm100
  • 48,078
  • 23
  • 82
  • 145
0

As everyone mentioned its used to define a block of code in C# and for a single line statement it doesn't matter whether you have braces or not but its a good practice according to stylecop (which is used to enforce a set of style and consistency rules) to always have curly braces even if your statement is only single line.

SA1503: CurlyBracketsMustNotBeOmitted: http://stylecop.soyuz5.com/SA1503.html

Adarsh Shah
  • 6,755
  • 2
  • 25
  • 39