Tiny Tip: is vs. as

Today’s tip is a quick look at both not widely used C# operators and why prefer one to another..

Casting using is-operator: 

if(p is Product) // CLR?: Could i cast this to product?


      Product x = (Product)p; // CLR again??: Could i cast this to Product?


This work but comes with performance cost so you better use the as-operator as follows:

Casting using as-operator:

Product x = p as Product; // CLR?: Could i cast this to product?



     // your logic here..


Here the CLR checks for type compatibility only one time and as-operator never throw an exception only the result will be null if it’s not type compatible.

2 thoughts on “Tiny Tip: is vs. as”

  1. This is not necessarily true. In reality there may be a low chance that p is of type Product, in which case using “is”, is actually slightly faster. We’re talking about billionths of seconds here, so it only matters for really big loops.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>