简体   繁体   中英

What is the fastest way to get a property from an object after checking that the object isn't null?

What is the fastest way (in terms of minimizing the amount of code statements) to get a property from an object after checking that the object isn't null?

string s = null;

if (null != myObject)
{
    s = myObject.propertyName;
}

For reference: Wait for future C# 6.0 feature for null checking with possible ?. syntax:

string result = obj?.ToString();

For now: Use ternary operator :

string result = obj != null ? obj.ToString() : null;

C# does not have a null-propagating operator (although it has been discussed a few times). Frankly, "faster" is not likely to be a factor here, as it will typically end up in the same (or similar enough) IL, but I tend to use:

string s = myObject == null ? null : myObject.PropertyName;

the situation you describe is only one scenario where the operator is useful. It's also handy to replace constructs like this:

 if (value != null)
        {
            return value;
        }
        else
        {
            return otherValue;
        }

Or

return value != null ? value : otherValue;

with

return value ?? otherValue;

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