Tuesday, May 13, 2008 8:16 PM
I have noticed a few ways to handle converting datatypes. Does anyone know of any comprehensive articles that compare and contrast the different methods for handling this type of thing? I am curious about the advantages/disadvantages of casting, converting and Parsing to convert a datatype to a different type.
Thanks for any help.
Tuesday, May 13, 2008 8:22 PM
Casting is for type casting. So, for instance if you write
object a = 123;
then you can cast a to integer type using
int b = (int)a;
So it's not in the same line as converting and parsing. What about the last 2 you can see find of materials:
Tuesday, May 13, 2008 9:21 PM
Casting is our assertion (to the compiler) that an object really is something else - for example:
object obj= "abc";
string s = (string) obj; // cast
Here, we haven't created any new objects - we simply have a new variable that we know as a string; all that is involved is a runtime check that we are right...
The same example with integers (or any value-type in this way) is actually more "unboxing" than casting:
object obj = 123;
int i = (int) obj; // unbox
Is actually more an "unboxing" than a cast - but broadly similar... like a cast is needs to do some type-checking, but it also needs to do the unbox itself (another [very quick] operation, so *nominally* slower than a cast).
Conversion I interpret as using defined implicit or explicit conversion operator; we have changed the type (and created a new value), but in a way that the compiler can determine using static analysis:
decimal d = 123.4M;
int i = (int)d; // explicit conversion
float f = i; // implicit conversion
Executing a conversion is in reality executing a static method, so a stack needs to be prepared etc (unless the method gets inlined), and usually the code to convert between two types is a good few operations, so generally a bit slower than a cast, but still fairly quick.
Finally, parsing is interpreting a value from a form with no intrinsic relationship - i.e. there is no *direct* relationship between a string an an int, but we can parse:
string s = "123";
int i = int.Parse(s); // parse
(note a string isn't an int in terms of static analysis, so no cast/convert is possible). Parsing is usually the most expensive operation, as it needs to deal with things like string manipulation, cultures (is 12.100 equal to "12 point 1" (uk/us/etc), or "12 thousand 100" (a lot of Europe)), different candidate data formats, etc.