Simple question

  • Thread starter Thread starter Marty List
  • Start date Start date
M

Marty List

I have a C++ background, I'm new to C#, and I'm trying to clean up someone
else's code:

if(purge)
for(int j = 1; j < 2; j++)
try{
dumpster.Remove(1);
}
catch(Exception e){
WriteEvent(ErrorSource, e.StackTrace, LogType.Error);
}


Question #1: The "for" statement is pointless, since it only executes once,
correct?

Question #2: Should the "if" statement include braces, or will the catch block
execute without them?

If the braces are optional in this case, for clarity I think they should be
there anyway. This is how I would rewrite it, comments?

if(purge){
try{
dumpster.Remove(1);
}
catch(Exception e){
WriteEvent(ErrorSource, e.StackTrace, LogType.Error);
}
}
 
Hi,
I think that's pretty much correct. An 'if' statement only needs braces if
there is more than one statement that needs to be incl;uded in the if.
Otherwise, you don't need them, but like you said, it's good practice to use
braces for clarity. As for 'for', I don't know why that's there(?).

Ant.
 
That's incorrect. You will need the brackets for the if statement
because try and catch are two lines and are considered two seperate,
although equal level blocks. You don't need the brackets for the try or
the catch however, because only one statement is underneath each. For
example:

if(purge) {
try
dumpster.Remove(1);
catch(Exception e)
WriteEvent(ErrorSource, e.StackTrace, LogType.Error);
}
 
Actually, Try/Catch/Finally statements DO need the curly braces - all of
the time.... You'll get a compile error if you leave them out.
 
Marty List said:
If the braces are optional in this case, for clarity I think they should
be
there anyway.

I always uses braces even when it's optional. Mostly because I'm an expert
in adding code later and forgets to add the braces causing all kinds of
havoc.

The exception is for really simple statements/validations, but then I write
it on one line.

//What I don't do
if (age < 0)
age = 0;

//What I do
if (age < 0) age = 0;

Happy Coding
- Michael S
 
actually, you are wrong on both counts. the original code will compile fine
as is, while yours would not compile.
 
Michael S said:
I always uses braces even when it's optional. Mostly because I'm an expert
in adding code later and forgets to add the braces causing all kinds of
havoc.

The exception is for really simple statements/validations, but then I write
it on one line.

Thanks. I follow the same rule - If it looks good on one line then fine,
otherwise use braces. Like you I tend to add a line later and then spend 5
minutes trying to figure out what's wrong before it becomes painfully obvious.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top