Parse when you have a string containing a representation of a value. For example, when you have a user entering data into a TextBox and you need to use it as a number:
int value = int.Parse(myTextBox.Text);
Or preferably, use TryParse instead:
int value;
if (int.TryParse(myTextBox.Text, out value))
{
... use value
}
else
{
...report input error to user
}
Convert is the equivalent of Parse for strings, but it doesn't have a TryParse version, and it's slightly slower because it has to decide what type the parameter is: so if you have an
object
value to convert to an
int
Convert.ToInt32 will sort out the type and do it.
Casting does not do the same job: it's a syntactic sugar for "I know what this is, just make it so." - it doesn't change the actual object, it just changes the type of it (with minor exceptions, such as casting from a double to an int: that truncates the double and throws away the fractional part). But it won't change an object type unless they are castable: which means casting a derived type to an base type, or if an explicit cast operator exists (such as
double
->
int
and so forth). You can't use a cast to change a string to an int!
So:
1) If you have a string, use Parse, or TryParse (or TryParseExact)
2) If you have an object and you don't necessarily know what type it is, use Convert
3) If you do know what type it is and just need to refer to it in a different way, cast it.