What's the difference between using (int) variable or Convert.ToInt32 (variable)?

14

What's the difference between them? When is it best to use one or the other?

Examples:

string palavra = "10";
var numero = Convert.ToInt32(palavra); // ou (int)palavra ?

string palavra2 = "10.50";
var numero2 = (double)palavra2; // ou Convert.ToDouble(palavra2) ?

Note: the type int only used as an example, but I wanted to know in general about all types.

    
asked by anonymous 06.10.2015 / 15:39

2 answers

11

Cast

The (int) is a cast operator. It should only be used when there is certainty that the conversion will be successful. It can also only convert numeric values. In the example, cast for double will not work. He does not expect this kind of conversion.

cast must be available for the type being used and must be able to manipulate the input type. You can create this operator for your own types, although in a few cases it makes sense to do so. It is less useful than it seems. And does not perform well in some situations .

Convert

Convert.ToInt32() is a more thorough method that attempts to do the conversion more broadly,

06.10.2015 / 15:48
7

The (int)variável is a cast , which in the case of your question will not work for String (string), giving this error message:

  

CS0030 Can not convert type 'string' to 'double'

In case you can use Convert , but nowadays we use int.Parse or better int.TryParse .

Actually, Convert is not used very much these days because of some conversions problems ...

Example: ref site and all credits to Convert.ToInt32 vs Int32.Parse - Source Code

string s1 = "1234";
string s2 = "1234.65";
string s3 = null;
string s4 = "1234567891234567891123456789123456789";

Convert

result = Convert.ToInt32(s1); //-- 1234
result = Convert.ToInt32(s2); //-- FormatException
result = Convert.ToInt32(s3); //-- 0
result = Convert.ToInt32(s4); //-- OverflowException

Parse

result = Int32.Parse(s1); //-- 1234
result = Int32.Parse(s2); //-- FormatException
result = Int32.Parse(s3); //-- ArgumentNullException
result = Int32.Parse(s4); //-- OverflowException

Recommendation:

Always use methods related to type conversions int , use int.Parse or TryParse , and so on, bringing even greater clarity to your code. Convert has some methods that are used at some point in your code, but the frequency is low!

    
06.10.2015 / 16:00