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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With