Solved

when are these needed {}

Posted on 2012-12-20
1
193 Views
Last Modified: 2012-12-20
if (Project.ProjectID == 0) PID = 1; else PID = 2;

Why does this not have to have the brackets. When are they optional

if (Project.ProjectID == 0)
{
PID = 1;
}
else
{
 PID = 2;
}
0
Comment
Question by:Eamon
1 Comment
 
LVL 74

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
ID: 38710073
Brackets are optional if the body of your if (or else if, or else) consists of only one line. In your example, they would be optional, meaning this is exactly equivalent:

if (Project.ProjectID == 0) 
    PID = 1;
else 
    PID = 2;

Open in new window


The problem with using this approach is that it is easy to overlook the fact that this is only valid for single-ling bodies. For example, this would be a compilation error:

if (Project.ProjectID == 0) 
    PID = 1;
    PID = 2;
else 
    PID = 2;

Open in new window


The reason this fails is because the PID = 1; is the body of the if. Then you have a separate line of code in PID = 2;. Then you have an else that does not have an associated if (because of the intermediate PID = 2; line.

In your first example, this is actually very difficult to read. It would be easy for someone to completely overlook the else if they were scanning over your code.
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Introduction This article series is supposed to shed some light on the use of IDisposable and objects that inherit from it. In essence, a more apt title for this article would be: using (IDisposable) {}. I’m just not sure how many people would ge…
This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods. Introduction In one of my applications…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now