marc_s's answer is a little flawed, I see this code all the time so I want to emphasize the importance of the difference between these operators. is
is a boolean test to determine if an object is assignable to a certain type. as
checks to see if an object is assignable to a certain type and if it is, it returns that object as that type, if not, it returns null. marc_s's answer is really doing this
foreach(Control c in form.Controls)
{
if(c is Textbox)
HandleTextbox(c is Textbox ? (Textbox)c : null);
if(c is Listbox)
HandleListbox(c is Listbox ? (Listbox)c : null);
}
It is redundant to use is
with as
. When ever you use as
just replace it with the expression above, it is equivalent. Use is
with direct casts ()
or as
only by itself. A better way to write that example would be.
foreach(Control c in form.Controls)
{
if(c is Textbox)
HandleTextbox((Textbox)c);
//c is always guaranteed to be a Textbox here because of is
if(c is Listbox)
HandleListbox((Listbox)c);
//c is always guaranteed to be a Listbox here because of is
}
Or if you really like as
foreach(Control c in form.Controls)
{
var textBox = c as Textbox;
if(textBox != null)
{
HandleTextbox(textBox);
continue;
}
var listBox = c as ListBox
if(listBox != null)
HandleListbox(listBox);
}
A real world example that I run into all the time is getting objects from a storage area that only return type object. Caching is a great example.
Person p;
if (Cache[key] is Person)
p = (Person)Cache[key];
else
p = new Person();
I use as
much less in real code because it really only works for reference types. Consider the following code
int x = o as int;
if (x != null)
???
as
fails because an int can't be null. is
works fine though
int x;
if (o is int)
x = (int)o;
I am sure there is also some speed difference between these operators, but for a real application the difference is negligible.