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)