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:

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

…becomes:

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.

Auto-Implemented Properties

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

… becomes

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.

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.

Like this post? Share it!
Free WordPress Themes, Free Android Games