If you're new here, you may want to subscribe to my RSS feed. Thanks for visiting!

One of the best things about C# is that as the language and libraries expand thought is put into keeping things readable. Below I have listed 10 shorthands that you can use to make your code tighter and less wordy. No doubt you know one or more already — but do you currently use all ten of them ?

1. The ? conditional evaluation operator

I first read about the ? operator in the “The C Programming Language” book by Brian Kernighan and Dennis Ritchie (first published in 1978, but I didn’t get around to reading it until well into the second edition). So this isn’t anything new. But it IS handy. It allows you to compress a common if-then-else pattern into a single assignment.

int x = 10;
int y = 20;
int max;
if (x > y)
max = x;
else
max = y;

Using the (Question) ? Positive Answer : Negative Answer patterns the above can be rewritten as:

int x = 10;
int y = 20;
int max = (x > y) ? x : y;

2. Null-Coalesce operator (??)

How often do you test for null values in your code? Often? Then the null-coalesce operator (??) comes in handy. To see how it works consider the following code example:

Using the ?? operator we can make it even shorter. If the left hand side is null, the right hand side is assigned.

object cache = null;
object d = new object();
object e = c ?? d;

3. Object Initializers

After you create a new object you often have to assign one or more of its properties. With the introduction of C# 3.0 it is now possible to use object initializers to both improve the readability of this, and to shorten your code.

Often you will need to allocate a system resource such as a font, file handle, network resource etc. Each time you need such a resource there are three critical steps to go through: You acquire the resource, you use it, and then you dispose of it. If you forget to properly dispose of it you will have created a memory or resource leak. This is best illustrated through the following patterns:

// Allocate the resource
using (Font font1 = new Font("Arial", 10.0f))
{
// The bit where we use the resource
}
// Disposal is automatic

The using statement is intended to be used with objects that implement the “IDisposable” interface which in practice is all .NET objects that allocate and manage resources.

5. Aliases for long winded namespaces and types

The names of C# identifiers can become quite long. If you are doing Microsoft Office automation in C# you might want to do something simple like open MS Word and change a document. You can use the “using” statement to create an alias for either a class or a namespace.

A variable needs to have a value, it cannot be null. Sometimes it would be handy it was possible to assign “null” (eg. undefined) to a variable. .NET 2.0 introduced the Nullable generic that makes this possible. The following two lines produce exactly the same object:

Nullable<int> x = null;
int? x = null;

By putting a ? following a variable definition the compiler will wrap a Nullable<T> generic around the type.

7. Automatic Properties

C# 3.0 introduced automatic properties. A property typically consists of (but doesn’t have to) a private variable which is exposed to the outside world through getters and setters. The following is common example of this:

The C# compiler will automatically generate a backing variable and the correct get and set properties. Why is this useful? After all you could have just made a string variable in the class public instead.

By defining it as a property allows you to add the actual validation logic to your class at a later stage. The in-memory signature of the class won’t change which means that any external libraries compiled against your code will not have to be recompiled.

8. Type inference

In typical C# you will always carefully spell out your definitions:

string MyString = “Hello World”;

From the right side of the declaration it is obvious that only one type (string) will ever match this definition. So instead of us doing the work, why not let the compiler figure this out?

var MyString = “Hello World”;

The above definition will also create a string variable named “MyString”. It is important to note that C# is still strongly typed.There is no performance impact results from using type inference.

The compiler does all the work figuring out the data type at compile time. Of course this feature created two opposite camps, one that thinks var should be liberally applied, and another one that abhors the whole idea. The middle ground seems to be that var should be used there were its use is obvious.

This should make you glad that the compiler figured it all out for you. I wrote more about this in another post: Anonymous Types : The Basics.

9. Lambda Expressions

C# 2.0 introduced anonymous methods, which are methods defined inside a method. Incredibly powerful and a nice way to put all kinds of evaluation logic inside your code they had the drawback that they could be quite hard to read.

Func mySeniorStaffFilter = delegate(int a) { return a > 35; };

The above method takes an integer as a parameter, and returns a boolean. It checks if the staff member passed to it is older than 35. If so, it returns true.

Lamba expressions make things a little easier to read, while being functionally exactly the same:

Func mySeniorStaffFilter = a => a > 35;

Even better, you can define them anywhere a delegate would have fitted:

var SeniorStaff = Employees.Where(s => s.Age > 35);

10. string.IsNullOrEmpty

Not really a language feature, but a useful little library function in its own right. How often do you need to test if a string is empty? Or null? The string.IsNullOrEmpty method returns true if this is the case.

Optional and named parameters in C# 4.0

As a bonus a little on the upcoming C# 4.0 which will introduce optional and named parameters. It is quite difficult to see what all the hoopla is about until you realize what optional parameters will do to improve Office automation coding in C#:

Microsoft Office certainly uses a lot of optional parameters. Note that in the first example all parameters are passed by reference. They still are in the second example. Behind the scenes the C# compiler creates the appropriate temporary variables to pass on, saving us from having to hand add them to the code.

To give proper credit, the above example comes from a video on this subject by Mike Ormond on Channel 9.

The ?? operator is interesting (as I had never seen that before), but for the most part I actually prefer the wordy if/else versions (always with brackets too). I would expect every programmer to understand if/else immediately, but I could understand if someone didn’t immediately parse the operator equivalents, as it takes me just a little bit longer to parse them.

For much the same reasons I’ve never taken advantage of type-inference, but I do like the foreach example you gave. I could see that as being an advantage. I never quite understood the advantage of writing var myString = “Hello” as opposed to String myString = “Hello”, but more than once I’ve wondered what specific type an enumerator was going to return – usually I just take a stab at it and let the compiler tell me if I’m wrong.

Excellent post! I forgot about that null-coalesce operator – could come in handy :).

BTW, I like the way you have your code formatted – it’s something that I’m having a ridiculously hard time getting to work in WordPress. Perhaps you’d have a suggestion? I have the “SyntaxHighlighter Evolved” plugin working just fine, but my problem is that switching to the Visual Editor removes all of the padding to the code. If you could let me know how you add c# snippets to your blog, I’d love you for ever :D.

Great tips, a few in here that even I didn’t know. However I was reading your one tutorial on anonymous types and you mention using LINQ rather than lambda. I prefer using LINQ statements as they are more human readable “from S in Employees where S.Age > 35 select S” versus “Where( s => s.Age > 35)”. Any reason you chose to put Lambda in there rather than LINQ?

I’m also wearing of using var. It definitely helps to avoid repeating yourself but indicating variable types is not always repetitive. Sometimes it is part of code clarity. Developers just have to use it properly and many don’t