#578 – Using the as Operator to Do Type Conversions

The as operator attempts to convert an expression to a specified type, returning the value of null if the conversion fails.  It behaves similarly to doing the conversion using a cast, but does not throw an exception if the cast fails.

// (Terrier is a sub-class of Dog)

Dog d = new Dog("Fido", 5);
Terrier t = new Terrier("Jack", 17, "Crabby");
Dog d2 = t;

Dog dTest = d as Dog;   // ok
dTest = d as Terrier;   // null

dTest = t as Dog;       // ok
Terrier tTest = t as Terrier;   // ok

dTest = d2 as Dog;      // ok
tTest = d2 as Terrier;  // ok

Object oTest = d as object;    // ok
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

2 Responses to #578 – Using the as Operator to Do Type Conversions

  1. Pingback: #579 – Typical Pattern for Using as Operator « 2,000 Things You Should Know About C#

  2. Pingback: #580 – as Operator Can Generate Compile-Time Errors « 2,000 Things You Should Know About C#

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: