Wednesday, September 8, 2010

Keyboard shortcuts poster

Just found that the team at Microsoft has published a printable list of keyboard shortcuts for Visual Studio 2010. I have downloaded my copy for C#, and it will be on my desk by the morning. Don't doubt, this is a must have no matter how much time you spend with Visual Studio IDE.

You can download them here. Choose the file and format for your favorite language.

If you are using Visual Studio 2008 and missed the poster, you can download the keyboard shortcuts poster for C# here and VB here. Don't miss it!

Tuesday, September 7, 2010

Null-coalescing operator in C#

This is the first time I seriously took an opportunity to look at null-coalescing operator in C#. Introduced in C# 2.0, this is one cool operator that I have hardly put into practice. Well, until now but not anymore. :)

Null-coalescing operator is used to define a default value for nullable types as well as reference types. Let's look at an example.
loginName = loginName ?? "guest";
What we are doing here is using the null-coalescing operator to check whether "loginName" is null. If it is null, the default value "guest" is assigned to it. This could have been done otherwise using a if-else block:
if(loginName == null)
   loginName = "guest";
, or even using a ternary operator:
loginName = (loginName == null) ? "guest" : loginName;
But isn't the null-coalescing operator more sweeter version! In case of strings, I would advise you to use IsNullOrEmpty or IsNullOrWhitespace methods of string class. One way to make sure you get a trimmed login name, you could use a combination as above:
loginName = (string.IsNullOrWhiteSpace(loginName) ? null : loginName.Trim()) ?? "guest";
One more example can be when you need to know if a connection is initialized yet or not. And if not, initialize with the default connection string.
conn = conn ?? new SqlConnection(defaultConnectionString);
Lets look at one more example. Consider a method that sets an Employee status to active. The method also makes sure that if it is passed a reference to an employee not initialized yet, it creates a new active employee and returns it.
public Employee SetEmployeeActive(Employee emp)
{
    //if employee object is not initialized yet, initialize it
    emp = emp ?? (new Employee());
    emp.IsActive = true;

    return emp;
}
Happy null-coalescing!