简体   繁体   中英

Null Conditional Operator in C# 5

In c# 6, there is the new Null Conditional Operator, like so:

var name = p?.FirstName;

What can we use in c# 5 so that we don't have to resort to:

var name = null;
if(p != null)
    name = p.FirstName;

Lashane has the same idea I did. Using a conditional operator can save you some time

the basic idea is that you evaluate if something is true or false, and give the values you want to put in for either.

var name = p != null ? p.FirstName : null;

The above is saying: "If p,= null? conditional (.) set to p,FirstName when true, null when false"

https://msdn.microsoft.com/en-us/library/zakwfxx4(v=vs.90).aspx

I has a same idea. And this is what I did:

public static T IsNull<T>(this T value) where T : new()
{
    if (value != null)
        return value;
    else
        return new T();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM