Quantcast
Channel: 2,000 Things You Should Know About C# » as operator
Viewing all articles
Browse latest Browse all 6

#578 – Using the as Operator to Do Type Conversions

$
0
0

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

Filed under: Operators Tagged: as, as operator, C#, Operators

Viewing all articles
Browse latest Browse all 6

Trending Articles