The As Cast in C#

How many times have you seen code like this:

if (employee is SalariedEmployee)
var salEmp = (SalariedEmployee)employee;

pay = salEmp.WeeklySalary;

// ...

This is redundant because you are checking the type twice. Once in the is check and once in the cast. Whenever you find yourself going down this path, prefer the as cast. This handy cast will cast the type if the types are compatible, or return null if not:

var salEmployee = employee as SalariedEmployee;

if (salEmployee != null)
pay = salEmployee.WeeklySalary;

// ...

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s