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
?
I use 'as' as a handy shortcut in event handlers to get the sending object back when I can't know at design time the sender.
Here's another use-case to go into the Cabinet of Dr. Caligari ;-)
You can chain the
as
operator, as in:Why would you do such a thing? If you want null if its not a Label, but you want to treat them all as Control. Just casting Textbox and Label directly to Control would yield success for both, now it'll be null for unwanted types of Control. This is a shortcut method you won't need often but is occasionally handy.
An alternative use for the same is when you need
ToString()
on an object, but only when it is of the correct type, otherwise you want a default string. This is a scenario that I do encounter very often, esp. with POCOs. BecauseToString()
is virtual, this works:I used both keywords extensively in a WinForms app where there's a GUI to edit an invoice, each row in the
ListView
could contain different types of items (i.e., it could be a line item or a description, or ...). All the items I put in theListView
were derived fromListViewItem
, so then later on when I went to implement things like editing the selected item, I had to check which item type was selected (usingis
) to show the appropriate editing GUI.Here's one that comes up alot:
Intriguing question. Actually, I use them all the time.
is
is handy to find out whether an object is of a certain type, I use that occasionally in generics or in loops through objects that are of different types. It is also invaluable with Reflection.The other,
as
finds many more uses. It is often much safer to use then a normal cast: when it fails, it returns null, instead of an exception. I also find it clearer syntax and easier to use it, check the return value for null, then to add an exception block.Basically, what I mean to say is, I prefer this:
and this:
as opposed to this:
of course, this is just an example, but when I can avoid try / catch, I will. This also lets more room for real exceptions to get through.
C-style casts (like
(Foo)bar
) will throwInvalidCastException
if cast fails.as
, on the other hand, will yieldnull
(see this).is
operator is just used to test whether a run-time type of given instance is compatible with the type provided (see this).is
is used extensively in.NET System.ComponentModel namespace. More specifically, TypeConverter API relies heavily onis
operator to determine how to convert from one type to another.