Does C# 6 Elvis operator (null propagation) short circuit

点点圈 提交于 2019-12-10 17:42:12

问题


Why this c# code throws a null exception?

bool boolResult = SomeClass?.NullableProperty.ItsOkProperty ?? false;

Isn´t elvis operator supposed to stop evaluation (short circuit) once the NullableProperty evaluates to null?

In my understanding the line of code above is a shortcut for:

bool boolResult 
if(SomeClass != null)
    if(SomeClass.NullableProperty != null)
        boolResult = SomeClass.NullableProperty.ItsOkProperty;
    else
        boolResult = false;
else
    boolResult = false;

Did I assume wrong?

EDIT: Now I understand why I get it wrong, The line of code actually translates to something similar to:

bool boolResult 
if(SomeClass != null)
    boolResult = SomeClass.NullableProperty.ItsOkProperty;
else
    boolResult = false;

And throws because NullableProperty is null...


回答1:


You need to chain, since the NRE is on the second reference:

bool boolResult = SomeClass?.NullableProperty?.ItsOkProperty ?? false;


来源:https://stackoverflow.com/questions/30765145/does-c-sharp-6-elvis-operator-null-propagation-short-circuit

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!