3 ms·
It's best if you think about the reason that "as" was added to C#. It's so you can do this: Customer c = person as Customer; if (c != null) { // do
by jasonkester 16y ago
It's best if you think about the reason that "as" was added to C#. It's so you can do this:
Customer c = person as Customer;
if (c != null)
{
// do something
}
else
{
// not a customer. must be just a regular person. do something else
}
instead of this:
if (person is Customer)
{
Customer c = (Customer)person;
// do something
}
else
{
// not a customer. must be just a regular person. do something else
}
... and that's it. It's just somebody's idea of a little cleaner syntax, not having to cast twice to get where you want to be.
In that light, the author's second example is closest to correct. It's just missing the "else" bit to handle the case where the base object you get passed is not be the exact type you're looking for.