marc_s answer is a bit corrupted, I see this code all the time, so I want to emphasize the importance of the difference between these operators. is is a logical test to determine if an object can be assigned to a particular type. as checks if an object is assigned to a particular type, and if it is, it returns this object as this type; if not, it returns null. marc_s answer really does it
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); }
You cannot use is with as . When you use as , just replace it with the expression above, this is equivalent. Use is only with live translators () or as . It is best to write this example.
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); }
The real example that I come across all the time is getting objects from the storage area that return only an object of type. 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 int cannot be null. is working fine though
int x; if (o is int) x = (int)o;
I am sure that there is a certain difference in speed between these operators, but for a real application the difference is not significant.
Bob Nov 04 '09 at 12:22 2009-11-04 12:22
source share