tags:

views:

175

answers:

8

Possible Duplicates:
Direct casting vs 'as' operator?
Casting: (NewType) vs. Object as NewType

What is difference between normal typecasting and using “AS” keyword?

+11  A: 

Using as will fail gracefully if the object is the wrong type, and the resulting value will be null, where a normal cast would throw an InvalidCastException:

object x = new object();
string y = x as string; // y == null
string z = (string)x; // InvalidCastException
Bennor McCarthy
+1  A: 

as casting will nerer throw an exception, while usual cast can.

Object a = new Object();
String b = a as String;
if(b != null) // always false for this example.
{}
Sly
+1  A: 

Normal type cast may return IllegalTypeCast exception where as as will return null in that case.

srinivas reddy thatiparthy
+1  A: 
((Class2) obj)  // Throws exception when the casting cannot be made

Class2 C = obj as Class2  //  Will return NULL if the casting cannot be made
The King
A: 

as cannot be used with value types (non-nullable types).

For reference types...

expression as type

is really the same as

expression is type ? (type) expression : (type) null

except that expression is evaluated only once.

In a nod to Bill Clinton, by 'is' in 'expression is type', I mean 'is'.

Basically, as the other answers indicate, that means that as returns null when the cast would fail. However, it also returns null when the cast would succeed but the type is wrong.

Here is a somewhat silly example:

uint? u = 52;
int? i = (int?) u;   // 'i' is now 52

but

uint? u = 52;
object d = u;
int? i = d as int?;

What is the value of i? 52? Nope. It is null.

Why the object in there? Turns out I lied above when I explained 'as' in terms of 'is'.

Observe:

uint? u = 52;
int? i = (u is int?) ? (int?) u : (int?) null;

'i' is now null

uint? u = 52;
int? i = u as int?;

Oops. Compiler error. So, I guess the two statements are not exactly the same after all.

Justin
In short: is is is and as is also as is is.
Eric Lippert
Not only that but I got to write C# that uses '?' like Lisp uses parenthesis. :-)
Justin
+5  A: 

The use cases of the two operators are superficially similar, but semantically quite different. A cast communicates to the reader "I am certain that this conversion is legal and I am willing to take a runtime exception if I'm wrong". The "as" operator communicates "I don't know if this conversion is legal or not; we're going to give it a try and see how it goes".

For more on this topic see my article on the subject:

http://blogs.msdn.com/b/ericlippert/archive/2009/10/08/what-s-the-difference-between-as-and-cast-operators.aspx

Eric Lippert
It can communicate that, but not necessarily. I've used the `as` keyword when I am sure a conversion will work, because I just prefer looking at: `(myobj as MyType).SomeProperty` over `((MyType)myobj).SomeProperty` In this case, the way I've done it communicates that I'm willing to take a `NullReferenceException` at runtime if it doesn't. Just wanted to point out that it's a stylistic thing.
jasonh
@jasonh - Using `as` that way reads as stylisticly wrong to me. It would make we wonder why a cast wasn’t done. Also, an invalid cast exception would lead a developer to the problem faster than a null reference exception. I prefer Eric’s style on this.
Jeffrey L Whitledge
A: 

You will never get an converting exception if you using "as" keyword. The result of the convert will be null if you are trying an invalid convert.

Implicitly/explicitly convert can be used between classes/interfaces with inherit/implement relations, otherwise it will give a compile error. See example:

public class A {}
public class B {}
...
A a = new A();
//B b = (B)a;  //compile error:Cannot implicitly convert type 'A' to 'B'

Another situation of implicitly/explicitly convert is there is no relationship between class A and B, but you write an implicit/explicit operator yourself.

Danny Chen
A: 

Also, as can only be used with reference types. This is actually quite logical, since if the conversion fails, it returns false, and that is not a possible value for a value type.

So for value types, normal typecasting must be used.

Øyvind Bråthen