What is the difference between
string url = (string)data AND string url = data as string;
Which is a better way ?
What is the difference between
string url = (string)data AND string url = data as string;
Which is a better way ?
The first construct will throw an InvalidCastException
if the cast fails, whereas the as
operator will return null if the data
variable is not a string.
Which is a better way ?
It will depend on what you are trying to achieve.
Think of as
as an attempt to cast the object to a specific type. If it fails, the resulting variable will hold null
. Direct casting on the other hand is a 1 way ticket
cast, if it fails an exception will be thrown.
Essentially, they do the exact same thing when the object can be cast to the specific type, but in the event that your cast is invalid, one will throw an exception and the other will "fail gracefully".
Which one you use really depends on the scenario. If your variable is an integral part of the code (i.e, if there's no point in continuing with the proceeding code if the cast fails), just use a direct cast and handle the exception. However, there are cases where not throwing an exception and handling the null value is extremely useful as well.
as keyword is defensive cast, does not throw exception when there is one in casting