简体   繁体   中英

Does null conditional operator return false if null?

I have this conditional

if (item?.Value2?.GetType() != typeof(string) && item.get_Value() == 0)

I believe that if item is null the ?. operation will return null, which I believe will be resolved as false causing the condition to short circuit and all will be well ( item.get_Value() won't be called)

However I am not certain, I thought maybe I need to do it like so

if (item?.Value2?.GetType() ?? 0 != typeof(string) && item.get_Value() == 0)

but I think that might be overkill, is the first way safe from potential null reference exception?

item?.Value2?.GetType() will return null if item is null or Value2 is null .

The condition evaluated will be

if (null != typeof(string) && item.get_Value() == 0)

so the first condition will be resolved as true causing a NullReferenceException when item.get_Value() == 0 will be executed (but only when item is null , and not Value2 )

.Value2 is faster, but for cells formatted as Date or Currency, .Value2 returns Double, but .Value or .get_Value() return DateTime and Decimal. Both result in Double if the cell is numeric type, and String if the value is not numeric type or number formatted as text. The return type can also be Boolean for TRUE and FALSE, and Integer for errors.


if (0.0.Equals(item.Value2)) // if (item.Value2 is Double && (Double)(item.Value2) == 0.0) 

This might look strange, but it is the shortest and safest way to check if the run-time type is Double and equal to 0.0. (item is not null if it is the result of enumerating a Range)


As for the actual problem, to find the first 0 cell:

Range cell = range.Find(0, LookAt: XlLookAt.xlWhole);
if (cell != null) { /* ... */ }

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