First of all, these are not comparisons but conversions (casting) of data.
Is there any type of rule established to use one or the other?
Yes. Here I explain them to you:
string nombre = "1234";
int i = (int)nombre;
This is called Conversion Explicita (explicit casting ). This type of conversion is used when you specify explicitly to what type of data you want to convert an object. In your example, you are clearly expressing that you want to convert an object System.String
to System.Int32
.
To be able to make an explicit conversion, 2 conditions have to be fulfilled: that there is some kind of relationship between the object and the type of data to be converted, either by inheritance or by the implementation of a common interface or by loading the < a href="https://www.google.com.do/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0ahUKEwjcq-yN2_PVAhXEv1QKHbJtB7UQFggpMAA&url= https% 3A% 2F% 2Fmsdn.microsoft.com% 2Fes-en% 2Flibrary% 2Fms228498 (v% 3Dvs.90) .aspx & usg = AFQjCNEMtSzoecjZ_LXsW7p2EHhi3TmYEA "> explicit conversion operator or predict .
The structure System.Int32(int)
is an example of the implicit operator overload with the data type char
since you can convert a char
to int
without having to specify the type of data to convert:
char n = 'n'
int letra = n; // valido
While to convert from int
to char
you have to specify it explicitly:
int nNumber= 110;
char n = (char)nNumber;
In your example, the operation is not valid because none of the 2 conditions are met.
string nombre = "1234";
int i = Convert.ToInt32(nombre);
Convert.ToInt32 converts an object int
, long
, decimal
, bool
, char
, float
, byte
, DateTime
a System.Int32
. If the data type can not be converted to int
an exception FormatException
is thrown.
string nombre = "1234";
int i = Int32.Parse(nombre);
Convert a System.String
to Int32
. If the data type can not be converted to int
an exception FormatException
is thrown.
The only difference between these last 2 is the variety of overloads that Convert.Int32
offers.