Possible Duplicates:
Casting: (NewType) vs. Object as NewType
Why is the C# “as” operator so popular?
Hey,
I know this may be a silly question but this doubt came to me today.
What is the difference between doing
String text = (String) variable;
and
String text = variable as String;
?
A cast can do three things:
An
asoperation is almost always a reference conversion, the only exception being unboxing to a nullable type:Then there’s the behaviour with conversions which fail at execution time. So the differences are:
InvalidCastExceptionon failure;aswill result in the null value of the target type insteadascan’tascan only be used for unboxing if the target type is a nullable value type