When you want to change types most of the time you just want to use the traditional cast.
var value = (string)dictionary[key];
It's good because:
- It’s fast
- It’ll complain if something is wrong (instead of giving object is null exceptions)
So what is a good example for the use of as
I couldn't really find or think of something that suits it perfectly?
Note: Actually I think sometimes there are cases where the complier prevents the use of a cast where as
works (generics related?).
Use
as
when it's valid for an object not to be of the type that you want, and you want to act differently if it is. For example, in somewhat pseudo-code:Or optimization in LINQ to Objects (lots of examples like this):
So using
as
is like anis
+ a cast. It's almost always used with a nullity check afterwards, as per the above examples.