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)
source share