If there is a difference, what is the difference between the two ways of doing the following cast?
In this case e
is a GridViewRowEventArgs
object.
GridView gv = (GridView)e.Row.FindControl("gv"); //first way GridView gv2 = e.Row.FindControl("gv") as GridView; //second way
string cast = (string) x; string asOperator = x as string; The major differences between these are pretty well-understood: Casting is also used for other conversions (e.g. between value types); "as" is only valid for reference type expressions (although the target type can be a nullable value type)
The is operator returns true if the given object is of the same type, whereas the as operator returns the object when they are compatible with the given type. The is operator returns false if the given object is not of the same type, whereas the as operator returns null if the conversion is not possible.
The as operator can only be used on reference types, it cannot be overloaded, and it will return null if the operation fails. It will never throw an exception. Casting can be used on any compatible types, it can be overloaded, and it will throw an exception if the operation fails.
Direct cast is most common way of casting one type to another, however it yields exception if casting can't be done. Below is the example to demonstrate the same. object length = 3.2; int test = (int)length; //Fails in runtime.
The differences are:
InvalidCastException
.as
operator fails, it just returns a null reference.as
with non-nullable value types (e.g. you can't do "o as int
").as
can be used to unbox to a nullable value type.)EDIT: I've written elsewhere about when I feel it's appropriate to use which operator. That might be worth a read...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With