Type Conversions
- Note:
When to use which method -
If you are converting from a string use parse.
If you are converting from another type use a cast or implicit conversion.
If a cast is not possible, or you are unsure of the types involved use Convert.
Implicit Conversions
In C# type conversions can be implicit if the conversion is considered safe.
For example converting an integer to a decimal.
In the above example the integer is converted from an integer to a decimal as the conversion is considered safe.
Casting
A cast is explicit when the conversion isn't done implicitly by the compiler, and then you must use the cast operator
The syntax for this is placing the required type in brackets before the variable name.
Parse & TryParse
Parsing is a method to convert a string into another type.
The above example will convert the string "12" and converts it to the int 12.
The above example will convert the string into a DateTime object.
The TryParse returns a bool stating if parsing the input would be successful as well as the result or a default value if unsuccessful.
This is beneficial as if the parse method is unsuccessful it will result in an error.
In the above example if the user entered a number string the value of isParsing successful would be true and the value of the number variable will be set to the parsed entered value.
If the user entered a value that could not be parsed to an int like a letter, then the value of isParsing Successful would be false and the value of the number field will be set to a default value, which for an int would be 0.
Convert Method
The Convert class provides methods to convert between types where simple casting is not possible. You should use convert if you're dealing with input whose types ypu don't know beforehand, or you are not certain your cast would ba valid.