New in C# 6.0: Null-Conditional Operator

Null checking can get real annoying real quick:

if (HttpContext.Current != null && HttpContext.Current.Session != null && HttpContext.Current.Session["UserId"] != null)
{
    return Int32.Parse(HttpContext.Current.Session["UserId"].ToString());
}
else
{
    return 0;
}

Thankfully, C# 6.0 introduces null-conditional operators, which allow us to transform this:

User user = GetUser();

string username;

if(user == null)
{
    // I know this is redundant, just go with me for example's sake
    username = null;
}
else
{
    username = user.Username;
}

Into this:

User user = GetUser();
string username = user?.Username;

With the null-coalescing (??) operator, we can even provide a default value in the same line:

User user = GetUser();
string username = user?.Username ?? String.Empty;

Rewriting our messy example above:

public static int GetUserId()
{
    return Int32.Parse(HttpContext.Current?.Session?["UserId"].ToString() ?? "0");
}

That looks nice, but why don’t we use a declaration expression to get rid of that nasty string literal:

public static int GetUserId()
{
    Int32.TryParse(HttpContext.Current?.Session?["UserId"].ToString(), out int result = 0);
    return result;
}

Ahhh, how beautiful.