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
?
If you're really never having to do casting then I you likely wouldn't have much use for these operators. In my experience, however, .NET programming calls for a lot of casting particularly when dealing with delegates where arguments are provided typed as 'object'. I think that the introduction of generics has helped cut down on the need for casting, but it's certainly something that I use pretty often. I might be "doing it wrong" but that's just been my experience.
So if you're going to do casting anyway I really like the 'is' operator for improved readability of the code. I'd much rather look at
then
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
andis
for me is that I can safely check whether a variable is of a given type usingis
without exceptions happening. Once I'm sure it's of a given type, I can safely and easily convert it to the type needed usingas
.What I basically did (simplified!) is a
and so on. Without
as
andis
this would be a lot messier, IMHO.Basically, you'll probably need or can make good use of
as
andis
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