As a long time Pascal and Delphi developer, I always line up my begin and ends thus :
begin
if x = y then
begin
...
...
end
else
for i := 0 to 20 do
begin
...
...
end;
end;
What drives me nuts is code formatted thus :
begin
if x = y then begin
...
...
end
else
for i := 0 to 20 do begin
...
...
end;
end;
When there are a few levels of compound statements I find this hard to read. The above code is ok, because it's not that complicated, but for consistency I'd prefer all begins and ends aligned.
As I start using c#, I find myself aligning curly brackets too. What's the norm in the C# world?
Edit :
Someone has pointed out that this is the type of question that shouldn't be asked on SO. I don't see why not. I'm in the process of setting up a coding guidelines document. I know I'll get some resistance to certain things, I'm hoping to get a few answers here, so I can be ready to meet that resistance head-on.
A compound statement (also called a "block") typically appears as the body of another statement, such as the if statement. Declarations and Types describes the form and meaning of the declarations that can appear at the head of a compound statement.
A compound statement is a sequence of zero or more statements enclosed within curly braces. Compound statements are frequently used in selection and loop statements. They enable you to write loop bodies that are more than one statement long, among other things. A compound statement is sometimes called a block.
A compound statement is simply a group of statements surrounded by curly braces. It can be used anywhere that a simple statement can be used to make a group of statements into a single entity. In the example above, the three assignment statements form a compound statement because they are enclosed in the curly braces.
I personally use:
if Condition then
begin
DoThis;
end else
begin
DoThat;
end;
See Object Pascal Style Guide.
In compound if statements, put each element separating statements on a new line: Example:
// INCORRECT
if A < B then begin
DoSomething;
DoSomethingElse;
end else begin
DoThis;
DoThat;
end;
// CORRECT
if A < B then
begin
DoSomething;
DoSomethingElse;
end
else
begin
DoThis;
DoThat;
end;
Here are a few more variations that are considered valid:
// CORRECT
if Condition then
begin
DoThis;
end else
begin
DoThat;
end;
// CORRECT
if Condition then
begin
DoThis;
end
else
DoSomething;
// CORRECT
if Condition then
begin
DoThis;
end else
DoSomething;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With