473,671 Members | 2,572 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

casting (best practice?)

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

Apr 4 '07 #1
2 2641
On Apr 4, 1:15 pm, kilik3...@gmail .com wrote:
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

Apr 4 '07 #2
On Apr 4, 8:29 am, "Jon Skeet [C# MVP]" <s...@pobox.com wrote:
On Apr 4, 1:15 pm, kilik3...@gmail .com wrote:
I have a question about who one should go aboutcastingtyp es inC#.
I have heard some writers and speakers call staticcastinga bad
practiceand 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 staticcastingOR 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
Cool.

Yup I meant to write cast + is (not as + is). Thanks for clarifying
this issue for me.
Apr 4 '07 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
3459
by: Jacob Jensen | last post by:
This question has probably been asked a million time, but here it comes again. I want to learn the difference between the three type cast operators: static_cast, reinterpret_cast, dynamic_cast. A good way to do this is by example. So I will give an example and please tell me what you think: I have a base class A with a virtual destructor, and a class B that is it inherits publicly from A and defines som extra stuff.
136
9315
by: Matt Kruse | last post by:
http://www.JavascriptToolbox.com/bestpractices/ I started writing this up as a guide for some people who were looking for general tips on how to do things the 'right way' with Javascript. Their code was littered with document.all and eval, for example, and I wanted to create a practical list of best practices that they could easily put to use. The above URL is version 1.0 (draft) that resulted. IMO, it is not a replacement for the FAQ,...
5
1810
by: Tom Carroll | last post by:
When assigning or testing equality between a type and a constant, should the constant be casted to the type? I.e. should fork() == -1 be written as fork() == (pid_t)-1? should uid = 45 be written as uid = (uid_t)45? Is the casting necessary? Does it increase portability? Browsing some projects, I noticed that -1 is casted but not other values, i.e. chown("somefile", 45, (gid_t)-1).
231
23111
by: Brian Blais | last post by:
Hello, I saw on a couple of recent posts people saying that casting the return value of malloc is bad, like: d=(double *) malloc(50*sizeof(double)); why is this bad? I had always thought (perhaps mistakenly) that the purpose of a void pointer was to cast into a legitimate date type. Is this wrong? Why, and what is considered to be correct form?
35
2679
by: ytrama | last post by:
Hi, I have read in one of old posting that don't cast of pointer which is returned by the malloc. I would like to know the reason. Thanks in advance, YTR
41
4949
by: SRR | last post by:
Why is it discouraged to explicitly typecast the void pointer returned by malloc(); function? For example: { int *p; p = (int*)malloc(2*sizeof(int)); /*Explicit casting is done, therfore it is said to be a bad practice*/ /*Some codes*/ }
6
4256
by: Ken Fine | last post by:
This is a basic question. What is the difference between casting and using the Convert.ToXXX methods, from the standpoint of the compiler, in terms of performance, and in other ways? e.g. this.ContentID = (int)ci.Conid; vs. this.ContentID = Convert.ToInt32(ci.Conid); I tend to use the latter form because it seems more descriptive to me, but it would be good to know what's best practice. I'm guessing those methods
5
2720
by: johanatan | last post by:
Does anyone know the reasons for the lack of an implicit casting operator in any greater depth than: A. Automatic conversion is believed to be too error prone. (from the FAQ at the bottom of: http://www.boost.org/libs/smart_ptr/shared_ptr.htm) Can anyone say specifically what about the implicit conversion would be dangerous? I can think of a few things that would require care about usage of smart pointers with implicit conversions,...
10
3776
by: Alex Vinokur | last post by:
Hi, Is it possible to do C++-casting from const pair<const unsigned char*, size_t>* to const pair<unsigned char*, size_t>* ? Alex Vinokur
0
8483
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8402
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8825
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8605
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6237
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5703
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4416
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2062
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1816
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.