Thursday 13 August 2015

Parse, TryParse, Convert

We've talked a lot about converting data between types, we talked about testing to see if our data was of a specific value or reference type using the "is" comparison, we used the "as" operator to convert one reference type into another nullable objects, we talked about implicit vs explicit casting.

Now the question is what do we do if we have a string that actually contains the value for a number or a date? well we can use the int.Parse() function or the DateTime.Parse() functions.


namespace pav.tryparse
{
    class Program
    {
        static void Main(string[] args)
        {
            var strInt = "123";
            int i = int.Parse(strInt);

            var strDate = "1/31/1984";
            var date = DateTime.Parse(strDate);
        }
    }
}


now that's great, but what if our string doesn't contain what we expect, let's for example say that we got our date from a European web service, that would return it in the dd/mm/yyyy format. well using the parse method in this fashion will throw a Format Exception or if we expected an int value of 123 but instead got the string "sdf".

to get around our problem we can use the tryParse methods


namespace pc.tryparse
{
    class Program
    {
        static void Main(string[] args)
        {
            var strInt = "123";
            int i;
            int.TryParse(strInt, out i);

            var strDate = "31/1/1984";
            DateTime d;
            DateTime.TryParse(strDate, out d);
        }
    }
}


this approach will first test to see if our string inputs represent the value of the types they want to be and if so then they are set to the out parameter.

Now there's also a static Convert class with static overloaded Convert functions

namespace pc.tryparse
{
    class Program
    {
        static void Main(string[] args)
        {
            var strInt = "123";
            int i = Convert.ToInt32(strInt);

            var strDate = "31/1/1984";
            DateTime d = Convert.ToDateTime(strDate);
        }
    }
}

these functions cover just about any standard conversion you'd want to make, however they introduce the Format Exception issue once again.