C#
is and as operators
Learn type testing with is and safe casting with as.
Type testing with is
The is operator tests whether an object can be converted to a given type. It returns a bool. The check if (animal is Dog) yields true when animal can be treated as a Dog.
The as operator performs a safe cast. If the cast fails it returns null instead of throwing. After Dog dog = animal as Dog;, dog is either a Dog instance or null. With as you check the result against null before using it.
A typical as usage
The common pattern is: cast with as first, then check for null. This avoids the InvalidCastException risk of a direct cast.
For example: you walk a List<Animal> and want to find the Dogs. Try as Dog and call Bark only when the result is not null. You skip non-matching items instead of throwing on them. This pattern is common in polymorphic collections.
Exercise Find Dog instances with as
Define an Animal class. Define Dog : Animal with a public void Bark() method that prints Console.WriteLine("Woof"). In Main build a List<Animal> with one Dog, one Animal, one Dog. In a foreach, try each item with as Dog and call Bark when not null.
Show example solution
Animal { public void Bark() { Console.WriteLine("Woof"); } }. In Main build List<Animal> { new Dog(), new Animal(), new Dog() }. foreach each item, Dog d = a as Dog;, if (d != null) d.Bark();
Example solution:
using System;
using System.Collections.Generic;
class Animal { }
class Dog : Animal
{
public void Bark()
{
Console.WriteLine("Woof");
}
}
class Program
{
static void Main()
{
var animals = new List<Animal> { new Dog(), new Animal(), new Dog() };
foreach (var a in animals)
{
Dog d = a as Dog;
if (d != null)
{
d.Bark();
}
}
}
}
Test yourself
-
Match each operator to its job
- is
- Tests a type
- as
- Returns a safe cast
- (T)
- Throws on bad cast
- typeof
- Yields the Type object
-
The safe cast operator
Dog dog = animal ____ Dog;
Show answer
Dog dog = animal as Dog;
-
What happens when as fails?
Cat c = animal as Cat;
// animal is actually a Dog
- InvalidCastException is thrown
- NullReferenceException is thrown
- c becomes null
- A compile error occurs
Show answer
c becomes null — Correct. as returns null on a failed cast, it does not throw.
Next lesson: Pattern matching for polymorphism