Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use a Cast or Convert

Tags:

c#

casting

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.

like image 287
Gage Avatar asked Jul 02 '10 19:07

Gage


People also ask

Is CAST or convert more efficient?

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.

What is difference between CAST and convert in mssql give example of CAST date?

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 .

How do you CAST and convert?

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.

What is CAST () and convert () functions in SQL Server?

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.


1 Answers

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.

like image 175
Greg Avatar answered Oct 07 '22 12:10

Greg