2

What is the difference between

string url = (string)data AND string url = data as string;

Which is a better way ?

VJOY
  • 3,752
  • 12
  • 57
  • 90
  • Repost of many other questions I mean duplicate : [What is the difference between the following casts in c#?](http://stackoverflow.com/questions/702234/what-is-the-difference-between-the-following-casts-in-c) – Bastardo Jun 11 '12 at 06:36

3 Answers3

6

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.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
3

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.

Jason Larke
  • 5,289
  • 25
  • 28
1

as keyword is defensive cast, does not throw exception when there is one in casting

Pravin Pawar
  • 2,559
  • 3
  • 34
  • 40