The (int)variável
is a cast, that in the case of your question will not work for String (string), giving this error message:
CS0030 Cannot Convert type 'string' to 'double'
In case you can use the Convert
, but today we use the int.Parse
or better yet int.TryParse
.
In fact the Convert
is not widely used nowadays due to problems of some conversions ...
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
Recommending:
Always use methods referring to type conversions
int
, utilize int.Parse
or TryParse
and so on, bringing even greater clarity to your code. The Convert
has some methods that are used at some point in your code, but, the frequency is low!
Who gave negative comment the reason. If the question is not appropriate I delete or modify.
– Joao Paulo
I did not deny, I think it is better that you put the example of the two in the question as code, in the title when I read had the impression of the
(int)
as something apart, I think you meant:var num = (int)valor;
– rray
Thanks @rray, I added some sample code.
– Joao Paulo