Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# NullReference Exception and ReSharper suggestion

This is what I have written:

if ((lstProperty[i].PropertyIdentifier as string).CompareTo("Name") == 0)

Resharper put me an error (I am new with ReSharper... I am trying it) and it suggests me :

  if (((string) lstProperty[i].PropertyIdentifier).CompareTo("Name") == 0)

Why is the second is NullException safe? For me both will crash if null value appear?

like image 809
Patrick Desjardins Avatar asked Dec 13 '22 06:12

Patrick Desjardins


1 Answers

The 'as' operator will return null if the cast cannot be executed, while a C-style cast will throw an exception if it can't cast.

I suggest breaking this out into multiple statements:

string propertyIdentifier = lstProperty[u].PropertyIdentifier as string;
if(propertyIdentifier != null && propertyIdentifier.CompareTo("Name") == 0)
{
    ... your if statement ...
}

Resharper shouldn't complain about this, and you also won't get a NullReferenceException if the PropertyIdentifier is null or not a string.

like image 147
jonnii Avatar answered Dec 29 '22 10:12

jonnii