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.