C # NullReference exception and ReSharper clause

Here is what I wrote:

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

Resharper gave me an error message (I'm new to ReSharper ... I'm trying it) and it offers me:

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

Why does the second throw a NullException? Will both fail for me if a zero value appears?

+4
source share
2 answers

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

I suggest breaking this down into several statements:

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

Resharper should not complain about this, nor will you get a NullReferenceException if the PropertyIdentifier is null or not a string.

+8
source

Both examples will succeed or fail in the same circumstances, and when they succeed, the behavior will be identical.

When they fail, the result will be slightly different: the second example fails a little earlier (when passing) and with a more specific exception ( InvalidCastException vs. NullReferenceException ).

The main advantage is debugging: when they fail, you have additional information about why in the second example this did not work out than in the first. In particular, if PropertyIdentifier null vs. non string , you can say in the second case, but not in the first case.

In addition, if you are in try/catch , you can handle the non- string case in a separate code path than with the null tag. However, you probably shouldn't code this path: if you are, you are doing something else wrong.

This can help illuminate the situation if you execute the following code in various cases:

 var propertyI = lstProperty[i]; var propertyIdentifier = propertyI.PropertyIdentifier; // pick one of these: var propertyIdentifierAsString = propertyIdentifier as string; var propertyIdentifierAsString = (string)propertyIdentifier; if (propertyIdentifierAsString.CompareTo("Name") == 0) 
+5
source

All Articles