#447 – Use as Operator to Get At an Object’s Interfaces

If a class implements an interface, you can assign a variable whose type is that class directly to a variable of the interface’s type.

            Cow bossie = new Cow("Bossie", 12);

            IMoo viaMoo = bossie;
            viaMoo.Moo();

However, there might be times when you have a variable of a more general type and the variable may or may not implement a particular interface. In these cases, you could use a dynamic cast to cast the object variable to the interface type.

            object objSomething = bossie;

            // Can't assign directly; need cast
            IMoo viaMoo = (IMoo)objSomething;
            viaMoo.Moo();

The only problem is that this cast will fail, throwing an InvalidCastException, if the object does not implement IMoo.  Instead, you can use the as operator, which essentially does the cast, but just returns null if the cast fails.

            IMoo viaMoo = objSomething as IMoo;
            if (viaMoo != null)
                viaMoo.Moo();
Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #447 – Use as Operator to Get At an Object’s Interfaces

  1. Good Explanation says:

    Good Explanation.. Thanks

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 )

Facebook photo

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

Connecting to %s

%d bloggers like this: