Posted by: Cirilo Meggiolaro | 11/17/2008

Tip of the day #34 – Safely casts for value type objects

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.

TryParse method

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.

How to…

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.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: