Google Search: c# instanceof

A couple of people have come to my site with the query "c# instanceof". I know how I get found for this. I copied an "instanceof" javascript method and talked about it in one of my entries.

The only relation to c# that I can think of would be the "is" and "as" keywords.

"is" can be used to test what type of object an object reference is. For instance [no pun intend, or thought of I think :)] a developer could write:if(m_car is MiniCooper){...

they would be saying that if the m_car variable is of the type MiniCooper then do something.

The "as" keyword is used to "cast" a type to another type. So you could write

if(m_car is MiniCooper){MiniCooper mc = m_car as MiniCooper;

The "as" keyword is slightly differnt to the Explicit cast (MiniCooper mc = (MiniCooper) m_car; because if the cast dosn't work with an "as" then the mc local variable will be null, rather than throwing an "InvalidCastException".

I hope this helps.

About Me: Paul Kinlan

I lead the Chrome Developer Relations team at Google.

We want people to have the best experience possible on the web without having to install a native app or produce content in a walled garden.

Our team tries to make it easier for developers to build on the web by supporting every Chrome release, creating great content to support developers on web.dev, contributing to MDN, helping to improve browser compatibility, and some of the best developer tools like Lighthouse, Workbox, Squoosh to name just a few.