Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# difference between casting and as? [duplicate]

Tags:

c#

casting

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


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.

As far as I know!

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


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.