I am curious to know what the difference is between a cast to say an int
compared to using Convert.ToInt32()
. Is there some sort of performance gain with using one?
Also which situations should each be used for? Currently I'm more inclined to use Convert
but I don't have a reason to go either way. In my mind I see them both accomplishing the same goal.
In some cases CAST performs better than PARSE, which performs better than CONVERT. In other cases, CONVERT performs better than CAST, which performs better than PARSE.
CONVERT is SQL Server specific, CAST is ANSI. CONVERT is more flexible in that you can format dates etc. Other than that, they are pretty much the same. If you don't care about the extended features, use CAST .
The Cast() function is used to convert a data type variable or data from one data type to another data type. The Cast() function provides a data type to a dynamic parameter (?) or a NULL value. The data type to which you are casting an expression is the target type.
Solution. The T-SQL language offers two functions to convert data from one data type to a target data type: CAST and CONVERT. In many ways, they both do the exact same thing in a SELECT statement or stored procedure, but the SQL Server CONVERT function has an extra parameter to express style.
Cast when it's really a type of int
, Convert when it's not an int
but you want it to become one.
For example int i = (int)o;
when you know o is an int
int i = Convert.ToInt32("123")
because "123" is not an int, it's a string representation of an int.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With