C# difference between casting and as? [duplicate]
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
:)
Solution 1:
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:
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.