Casting / AS

N

Niki Estner

C# programmers reference - as operator:
....
Remarks:
The as operator is like a cast except that it yields null on conversion
failure instead of raising an exception. More formally, an expression of the
form:

expression as typeis equivalent to:

expression is type ? (type)expression : (type)nullexcept that expression is
evaluated only once.

Note that the as operator only performs reference conversions and boxing
conversions. The as operator cannot perform other conversions, such as
user-defined conversions, which should instead be performed using cast
expressions.
 
J

John Wood

A good example of where you might use AS is when you're testing to see if an
instance implements a specific interface, and to get hold of that interface
instance at the same time.
eg.

IWalks walker = animal as IWalks;
if (walks!=null)
{
... do something with 'walker'
}

Which is a little bit more efficient (when the instance does support the
interface) than the equivalent code:

if (animal is IWalks)
{
IWalks walker = (IWalks)animal;
... do something with 'walker'
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top