There are many ways to convert to int, a lot depends on what your source is.
The biggest thing to remember is error checking, none of the methods is proof of a fool yourself, so you need to decide how you want to approach them.
(int), Convert.ToInt32(), int.Parse() , InvalidCastException, FormatException OverflowException, try/catch .
int.TryParse() / , out, .
int, , , Convert.ToInt32, :
public void TestFunction(object input)
try {
int value = Convert.ToInt32(input);
SomeOtherFunction(value);
}
catch (Exception ex) {
Console.WriteLine("Could not determine integer value");
}
}
, .ToString(), :
public void TestFunction(object input)
try {
int value = int.Parse(input.ToString());
SomeOtherFunction(value);
}
catch (Exception ex) {
Console.WriteLine("Could not determine integer value");
}
}