casting (best practice?)

K

kilik3000

Hi All,

I have a question about who one should go about casting types in C#.
I have heard some writers and speakers call static casting a bad
practice and recommend using "as" and "is". That's fine.

However in most of the production code that I see, programmers use
either static casting OR use the "as" keyword without using the "is"
keyword first to verify that the object actually supports the desired
type.

What gives?

Is this just laziness or is something gained in brevity by only using
the static cast or the "as" keyword.

-Thx
 
J

Jon Skeet [C# MVP]

I have a question about who one should go about casting types in C#.
I have heard some writers and speakers call static casting a bad
practice and recommend using "as" and "is". That's fine.

It's not fine in my view, without an explanation of *why*.

I use "as" instead of "is + cast" and then only when it's valid for it
not to be true. So for instance, I'd do:

object o = GetSomeObject();
String x = o as String;
if (x != null)
{
// So something with x
}
else
{
// Do something else
}

If it's an error condition for o *not* to be a string, however, I'd
just cast - that way an appropriate exception will be generated in
that error case.
However in most of the production code that I see, programmers use
either static casting OR use the "as" keyword without using the "is"
keyword first to verify that the object actually supports the desired
type.

If you're going to use "as" there's no point in doing "is" first,
really.
Is this just laziness or is something gained in brevity by only using
the static cast or the "as" keyword.

The point is to avoid two runtime checks, which is what you get from is
+cast. "as" gives you one cast and then a cheap nullity check.

Jon
 
K

kilik3000

It's not fine in my view, without an explanation of *why*.

I use "as" instead of "is + cast" and then only when it's valid for it
not to be true. So for instance, I'd do:

object o = GetSomeObject();
String x = o as String;
if (x != null)
{
// So something with x}

else
{
// Do something else

}

If it's an error condition for o *not* to be a string, however, I'd
just cast - that way an appropriate exception will be generated in
that error case.


If you're going to use "as" there's no point in doing "is" first,
really.


The point is to avoid two runtime checks, which is what you get from is
+cast. "as" gives you one cast and then a cheap nullity check.

Jon

Cool.

Yup I meant to write cast + is (not as + is). Thanks for clarifying
this issue for me.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top