Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between casting and using "as" in C#?

Tags:

c#

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 
like image 558
Xaisoft Avatar asked Mar 31 '09 17:03

Xaisoft


People also ask

What is difference between casting and as C#?

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)

What is the main difference between the is and as operators?

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.

How is the as keyword used How is it different from casting?

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.

What is direct casting in C#?

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.


1 Answers

The differences are:

  • If a cast fails, it throws an InvalidCastException.
  • If the as operator fails, it just returns a null reference.
  • You can't use as with non-nullable value types (e.g. you can't do "o as int").
  • The cast operator is also used for unboxing. (as can be used to unbox to a nullable value type.)
  • The cast operator can also perform user-defined conversions.

EDIT: I've written elsewhere about when I feel it's appropriate to use which operator. That might be worth a read...

like image 132
Jon Skeet Avatar answered Sep 21 '22 19:09

Jon Skeet