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?

if(x!=null)

{

     // 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.

Published Mon, Oct 8 2007 5:33 AM by Adel Khalil
Filed under: , , ,

Comments

# Tiny Tip: is vs. as

Monday, October 08, 2007 4:47 AM by DotNetKicks.com

You've been kicked (a good thing) - Trackback from DotNetKicks.com

# Is vs. As Performance

Monday, October 08, 2007 6:35 AM by Joel Ross

Is vs. As Performance

# re: Tiny Tip: is vs. as

Monday, October 08, 2007 4:30 PM by Adel Khalil

make sense -:)

# Cheap payday loan.

Sunday, January 24, 2010 6:57 PM by Cheap payday loan.

Cheap payday loan.

# re: Tiny Tip: is vs. as

Wednesday, September 08, 2010 3:17 PM by Stephen Oberauer

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 Comment

(required) 
(required) 
(optional)
(required) 
Please add 8 and 7 and type the answer here: