Tip #33 explained how to perform safely casts for reference type objects. Let’s explore now how to perform checks for value types, especially numeric types.
The .NET framework provides the TryParse method that based on a string representation of the object converts to an output type. The method definitely will help you to avoid invalid cast exceptions to be thrown.
The TryParse method has two overloads. The example below represents the overloads for an integer type.
bool TryParse(string, out int)
bool TryParse(string, System.Globalization.NumberStyles, System.IFormatProvider, out int)
You may have realized that both overloads have in common:
1. A string parameter that represents the object to cast;
2. An output numeric type that is the result of the cast;
3. A Boolean value as the return type.
Checking the cast result
You have two options to check if the cast has performed properly. You can either check the return value from the method or check the output value. I think the first way more efficient and elegant.
To access the TryParse method you have to type <numeric type>.TryParse. The following code checks if a decimal value is valid and assign the result of the cast to a decimal variable:
string a = “123.57”;
decimal b = 0;
if (decimal.TryParse(a, out b))
// b = 123.57
It’s important to say that not only value types have the TryParse method available. You will find the method available for a large number of objects.