views:

470

answers:

2

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?

+8  A: 

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.

jonnii
This is what I thought ! Thanks
Daok
+5  A: 

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 slightly earlier (at the cast), and with a more specific exception (InvalidCastException vs. NullReferenceException).

The main benefit is for debugging: when they fail, you have more information about why it failed in the second example than in the first. Specifically, if the PropertyIdentifier is null vs. non-string, you can tell in the second case, but not in the first case.

Also, if you are in a try/catch, you can handle the non-string case in a separate code path than the null case. However, you probably shouldn't be coding this way: if you are, you're doing something else wrong.

It might help illuminate the situation if you step through the following code in the 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)
Jay Bazuzi
Thank for the information about the try/catch +1
Daok