Reputation: 140753
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?
Upvotes: 4
Views: 746
Reputation: 46496
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)
Upvotes: 5
Reputation: 28312
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.
Upvotes: 8