56

Possible Duplicate:
What is the difference between the following casts in c#?

In C#, is a there difference between casting an object or using the as keyword? Hopefully this code will illustrate what I mean...

String text = "Hello hello";
Object obj = text; 

String originalCast = ((String)obj).ToUpper();
String originalAs = (obj as String).ToUpper();

Thanks

:)

Community
  • 1
  • 1
  • Exact dupe of http://stackoverflow.com/questions/702234/what-is-the-difference-between-the-following-casts-in-c and many many others – annakata Jun 05 '09 at 10:44
  • duplicate of http://stackoverflow.com/questions/2483/casting-newtype-vs-object-as-newtype – pirho Jun 05 '09 at 10:45

4 Answers4

105

as will never throw a InvalidCastException. Instead, it returns null if the cast fails (which would give you a NullReferenceException if obj in your example were not a string).

Bakudan
  • 19,134
  • 9
  • 53
  • 73
Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
23

Other than InvalidCastException that's already mentioned...

as will not work if the target type is a value type (unless it's nullable):

obj as int // compile time error.
Mehrdad Afshari
  • 414,610
  • 91
  • 852
  • 789
9

As far as I know!

Using 'as' will return null if the 'cast' fails where casting will throw an exception if the cast fails.

Lewis
  • 5,769
  • 6
  • 30
  • 40
5

Using 'as' will not throw an exception if the obj is not a String. Instead it'll return null. Which in your case will still throw an exception since you're immediately referencing this null value.

Paul Mitchell
  • 3,241
  • 1
  • 19
  • 22