A real use for `as` and `is`

c#, keyword, language-features

Solution

I had to write code to enumerate over all the controls placed on a ASP.NET webform and perform certain operations on specific controls, e.g. add a background color to all Textboxes, and so on.

The main benefit of `as` and `is` for me is that I can safely check whether a variable is of a given type using `is` without exceptions happening. Once I'm sure it's of a given type, I can safely and easily convert it to the type needed using `as`.

What I basically did (simplified!) is a

foreach(Control c in form.Controls)
{
   if(c is Textbox)
      HandleTextbox(c as Textbox);

   if(c is Listbox)
      HandleListbox(c as Listbox);
}

and so on. Without `as` and `is` this would be a lot messier, IMHO.

Basically, you'll probably need or can make good use of `as` and `is` if you're dealing with polymorphism a lot - if you have lists of things that can be any number of types, like controls on a page in my example. If you don't have or don't use polymorphism a lot, you're unlikely to encounter the need for those operators.

Marc

Problem

I have -never- used `as` or `is` in C# or any language that supports the keyword. What have you used it for? I dont mean how do i use it i mean how have you actually need it? I also got away with doing no typecasting in a fairly large c++ project (i was proud). So considering i almost never typecast why do i need the keyword `as` or `is`?

Original source