Quantcast
Viewing all articles
Browse latest Browse all 6

#579 – Typical Pattern for Using as Operator

When you use the as operator to attempt to convert an expression to a particular type, you typically follow the pattern shown below.

In most cases, you have a variable of a base class that stores some object and you use the as operator to determine if it stores an object of a particular derived type.  In the example below, Terrier is a class that inherits from Dog.

            // Dog variable referring to object of type Terrier
            Dog d = new Terrier("Jack", 17, "Crabby");

            // Elsewhere in our code, we have variable
            // of type Dog and want to see if it refers to a
            // Terrier.
            Terrier t = d as Terrier;
            if (t != null)
                t.TerrierMethod();

You can do the same thing with the is operator, though it is a little less efficient, because it actually does the type conversion twice.

            // A bit less efficient
            if (d is Terrier)
                ((Terrier)d).TerrierMethod();

Filed under: Operators Tagged: as, as operator, C#, Operators Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.

Viewing all articles
Browse latest Browse all 6

Trending Articles