473,573 Members | 2,924 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

basic q: What are the differences between casting and Convert.ToXXX methods

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
are more expensive computationally .

-KF

Aug 27 '07 #1
6 4249

The difference it terms of functionality is shown in the following examples:

object a = "45"; // a is of type String
int b = (int)a; // InvalidCastExce ption is thrown
int c= Convert.ToInt32 (a); // c will contain 45

string d = "45";
int e = (int)d; // compiler error
int f = Convert.ToInt32 (d); // f will contain 45

string g = "test";
int h = Convert.ToInt32 (g); // FormatException is thrown because
Convert.ToInt32 will attempt to call Int32.Parse

long i = long.MaxValue;
unchecked
{
int j = (int)i; // OverflowExcepti on is thrown;
int k = Convert.ToInt32 (i); // OverflowExcepti on is thrown
}
checked
{
int l = (int)d; // f will contain -1
int m = Convert.ToInt32 (i); // OverflowExcepti on is thrown
(checked/unchecked doesn't affect Convet.ToXXX methods)
}
Depending on which overload of Convert.ToXXX you are calling, the
performance can be a bit slower than type casting (in case of the overload
that takes an object as a parameter) and functionality can be different, but
in many cases performance should be the same assuming that the JIT compiler
will inline the Convert.ToXXX calls.

Regards,
Sherif
"Ken Fine" <ke*****@newsgr oup.nospamwrote in message
news:%2******** ********@TK2MSF TNGP04.phx.gbl. ..
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
are more expensive computationally .

-KF

Aug 27 '07 #2
Well, casting is done by the compiler itself whereas Convert.To.... is a
method call. Performance-wise, the cast is generally preferred.

Convert.To, I find, is generally more handy for converting strings to
numbers. I rarely use it for anything else. I don't know that I've ever used
it to cast from one number to another. I don't really see that there's any
advantage and the casting looks cleaner and easier to read, in my opinion.

"Ken Fine" <ke*****@newsgr oup.nospamwrote in message
news:%2******** ********@TK2MSF TNGP04.phx.gbl. ..
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
are more expensive computationally .

-KF

Aug 27 '07 #3
Sherif,

I think checked and unchecked are backwards :)

System.Convert methods also perform rounding. For instance here is
some disassembly

public static int ToInt32(double value)
{
if (value >= 0)
{
if (value < 2147483647.5)
{
int num = (int) value;
double num2 = value - num;
if ((num2 0.5) || ((num2 == 0.5) && ((num & 1) != 0)))
{
num++;
}
return num;
}
}
else if (value >= -2147483648.5)
{
int num3 = (int) value;
double num4 = value - num3;
if ((num4 < -0.5) || ((num4 == -0.5) && ((num3 & 1) != 0)))
{
num3--;
}
return num3;
}
throw new
OverflowExcepti on(Environment. GetResourceStri ng("Overflow_In t32"));
}

-James



Aug 27 '07 #4
Yes, you are right :) Sorry about that.

"james" <ja********@gma il.comwrote in message
news:11******** *************@r 29g2000hsg.goog legroups.com...
Sherif,

I think checked and unchecked are backwards :)

System.Convert methods also perform rounding. For instance here is
some disassembly

public static int ToInt32(double value)
{
if (value >= 0)
{
if (value < 2147483647.5)
{
int num = (int) value;
double num2 = value - num;
if ((num2 0.5) || ((num2 == 0.5) && ((num & 1) != 0)))
{
num++;
}
return num;
}
}
else if (value >= -2147483648.5)
{
int num3 = (int) value;
double num4 = value - num3;
if ((num4 < -0.5) || ((num4 == -0.5) && ((num3 & 1) != 0)))
{
num3--;
}
return num3;
}
throw new
OverflowExcepti on(Environment. GetResourceStri ng("Overflow_In t32"));
}

-James



Aug 27 '07 #5
Thanks everyone! I appreciate the detailed examples, very succinct and
clear.

-KF

"pedrito" <pixbypedrito at yahoo.comwrote in message
news:Lt******** *************** *******@giganew s.com...
Well, casting is done by the compiler itself whereas Convert.To.... is a
method call. Performance-wise, the cast is generally preferred.

Convert.To, I find, is generally more handy for converting strings to
numbers. I rarely use it for anything else. I don't know that I've ever
used it to cast from one number to another. I don't really see that
there's any advantage and the casting looks cleaner and easier to read, in
my opinion.

"Ken Fine" <ke*****@newsgr oup.nospamwrote in message
news:%2******** ********@TK2MSF TNGP04.phx.gbl. ..
>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.Content ID = (int)ci.Conid;
vs.
this.Content ID = 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 are more expensive computationally .

-KF

Aug 29 '07 #6
(int) <doubleis a LOT faster than Convert.ToInt32 (<double>)

YMMV with other types of parameters.

Hilton
Sep 16 '07 #7

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

Similar topics

1
300
by: thomson | last post by:
Hi all, Can any one please explain what is the difference between Convert.ToInt32(somevalue),int.Parse(somevalue) and (int)somevalue thanks in Advance
7
30766
by: Jim Bancroft | last post by:
Hi everyone, A basic one here, I think. I haven't found the pattern yet, but sometimes when I cast a variable to another type using the "C" style cast operator the compiler refuses to play along. It says it's an invalid cast. However, if I use the Convert.ToInt32() method (for example) things will work. At least, that's how it appears to...
61
4531
by: Ken Allen | last post by:
I am relatively new to .Net, but have been using VB and C/C++ for years. One of the drawbacks with VB6 and earlier was the difficulty in casting a 'record' to a different 'shape' so one could perform different manipulations on it. For example, I have a complex data structure, which I can represent in a VB6 TYPE declaration, but I cannot...
8
7345
by: John A Grandy | last post by:
could someone please discuss the pros and cons of CType(MyDouble,Decimal) versus Convert.ToDecimal(MyDouble) .... and other such conversions ...
23
3494
by: René Nordby | last post by:
Hi there, Is there anyone that knows how to do the following? I have a class A and a class B, that 100% inherits from class A (this means that I don't have other code in class B, than the Inherit statement).
13
3016
by: usenet | last post by:
How and where can one find out about the basics of VB/Access2003 syntax? I am a died in the wool C/C++/Java Linux/Unix programmer and I am finding it difficult to understand the program format for accessing objects, controls, etc. in VB/Access2003. In particular where will I find explanations of:- Actions, Functions, Methods,...
5
2299
by: Charlie Brown | last post by:
Which is best to use in terms of performance/proper usage. Convert.ToDateTime(strDate) CType(strDate, DateTime) CDate(strDate)
9
1960
by: pauldepstein | last post by:
#include <iostream> using namespace std; int main() { int testNum; char *ptr; testNum = 1; ptr = (char*)(&testNum);
4
3084
by: Chris Asaipillai | last post by:
Hi there My compay has a number of Visual Basic 6 applications which are front endeed onto either SQL Server or Microsoft Access databases. Now we are in process of planning to re-write these applications into Visual Basic.Net. My managers main thought is that Visual Basic 6 is (or has!) stopped being supported by Microsoft.
0
7705
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...
0
8205
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...
1
7796
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...
0
8074
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5294
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...
0
3734
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
2223
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1310
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1044
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...

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.