C# difference between casting and as?

C#Casting

C# Problem Overview


> 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

:)

C# Solutions


Solution 1 - C#

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).

Solution 2 - C#

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.

Solution 3 - C#

As far as I know!

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

Solution 4 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser110714View Question on Stackoverflow
Solution 1 - C#Matthew FlaschenView Answer on Stackoverflow
Solution 2 - C#mmxView Answer on Stackoverflow
Solution 3 - C#LewisView Answer on Stackoverflow
Solution 4 - C#Paul MitchellView Answer on Stackoverflow