Tuesday, April 21, 2015

Null propagation in C# 6.0

Today I read ( http://www.volatileread.com/Wiki?id=2104 ) about the null propagation Operator ?. ... a C# 6.0 feature what enables you the possibility to make things like

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
string invalidResult = string.Empty;
 
if(this.CurrentUser != null)
{
    if(this.CurrentUser.Name != null)
    {
        return this.CurrentUser.Name;
    }
    else
    {
        return invalidResult;
    }
}
else
{
    return invalidResult;
}

in only one simple statement:


1
return this.CurrentUser?.Name ?? string.Empty;

... semantically "?." means "if not null evaluate property, else return null". 


cool stuff...

kind regards,
Daniel

No comments: