#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();
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.

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 )

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: