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