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 10-08-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 -:)

Leave a Comment

(required) 
(required) 
(optional)
(required)