tags:

views:

335

answers:

4

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

:)

+12  A: 

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

Matthew Flaschen
His example wouldn't give NullReferenceException.
Blindy
@Blindy - yes it would. He's trying to do a ToUpper() on what could potentially be a null object.
rein
Thanks, thought it might of been just shorthand!
Chalkey
+3  A: 

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
+6  A: 

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  A: 

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