10 C# Shorthands that improve productivity

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:

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

if (c != null)
e = c;
else

It is obvious that we can rewrite this using the single ? operator :

object cache = null;
object d = new object();

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();

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.

Customer c = new Customer();
c.Name = "James";

can be written as:

c.Address = "204 Lime Street";

4. The using statement

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:

// 1. Allocation of the object
Font font1 = new Font("Arial", 10.0f);
try
{
// 2. The bit where we use the resource
}
finally
{
// 3. Disposal of the object
if (font1 != null)
((IDisposable)font1).Dispose();
}

The using statement allows us to compress this down to:

// 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.

using Word = Microsoft.Office.Interop.Word;
...
Word.Application = new Word.Application() { Visible = True; }

6. Nullable objects

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 x = null;
int? x = null;

By putting a ? following a variable definition the compiler will wrap a Nullable 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:

public class Person
{
private string _firstName;
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
}

From C# 3.0 on we can reduce the above to:

public class Person
{
public string Firstname { get; set; }
}

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.

var SeniorStaff = Employees.Where(s => s.Age > 35);
foreach(var Member in SeniorStaff)
Console.WriteLine("Name: {0} Age: {1}",Member.Name,Member.Age);

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.

if (String.IsNullOrEmpty(s) == true)
return "is null or empty";
else
return String.Format("(\"{0}\") is not null or empty", s);