Thursday, May 05, 2005

Scott Bellware's Excellent C# Coding Style

Scott Bellware has put together an excellent C# Code Style Guide. His recommendations are consistent with my coding style except for one.

Under the section Returning Values I prefer:

if (condition)
{
return x;
}

return y;

over:

return (condition ? x : y);

Because return skips the execution of the remaining statements within a method (except for those statements in the finally block), using the former style allows you to, later on, add code easily before the second return statement.

The ternary operator is best avoided whenever possible. There is one situation that I could think of where a ternary operator is more readable then the if-else block:

if (x > 0)
{
y = x;
}
else
{
y = z;
}

should be written as:

y = (condition > 0 ? trueExpression : falseExpression);

But do NOT use this if trueExpression or falseExpression is an expression that contains more than an identifier, i.e.:

y = (x > 0 ? x + 1 : z - 1);

0 Comments:

Post a Comment

<< Home