Here are some of my favorite tips and tricks for C#.

The Ternary Operator

When writing a simple if-else statement, I love using the little-known ternary operator in C#. It can consolidate like 10 lines of uselessness in to one. The format is: <variable> = <condition> ? <value to use if true> : <value to use if false>

Here is an example. This simple yet lengthy if-else statement:

[C#] string result;

if (foo > bar)
{
result = “i pity the foo!”;
}
else
{
result = “it’s bar time!”;
}

…becomes:

[C#] string result = foo > bar ? “i pity the foo!” : “it’s bar time!”;

 

The Null Coalescing Operator

In the same vein as the Ternary Operator, I use this little guy all the time. It checks for a null in the value, and if encountered it uses the alternate value.

[C#] string result = foo ?? string.Empty;

Auto-Implemented Properties

Most people already know about this little shortcut when creating public properties.

[C#] private _isValid;

public bool IsValid
{
get { return _isValid; }
set { _isValid = value; }
}

… becomes

[C#] public bool IsValid { get; set; }

XML Documentation Comments

Using XML Documentation Comments in common methods like in a DAL or BLL are great for enabling useful IntelliSense. This is especially helpful if many developers are using the classes, or you are building an API. See MSDN – Recommended Tags for Documentation Comments for some good tags and how to use them. You can also generate HTML documentation directly from the source if you use this consistently, which is great for APIs and standalone DLLs that will be used elsewhere. GhostDoc is also a cool tool that helps generate XML Documentation Comment tags for already written procedures.

[C#] /// <summary>
/// Evaluates a data set for containing valid data per business logic rules
/// </summary>
/// <param name=”ds”>The System.Data.DataSet containing the data to evaluate.</param>
/// <param name=”enforceRequired”>A System.Boolean indicating if required fields are enforced. (true indicates required field requirements are enforced.)</param>
/// <param name=”allowDefaults”>A System.Boolean indicating if default values are accepted. (true indicates default values are accepted.)</param>
/// <returns>A System.Boolean indicating if the data is valid. (true indicates the data is valid.)</returns>
public bool IsDataValid(DataSet ds, bool enforceRequired, bool allowDefaults)
{
// Do stuff
}

The IntelliSense looks like this:

Preprocessor Directives

There are tons of these special hash-tag preprocessor directives. Most are useful for enabling some special code during debugging, but having it automatically be removed upon release compilation. Other than those, I like the #region tag for organizing sections of code. See more at MSDN – C# Preprocessor Directives.

Need to test the height of this box....

Social Wall