All types in the .Net framework have a Parse method. This takes a string and tries to translate it into a value of the intended type. Like this
int i = int.Parse("7");
This will throw an exception when the contents of a string cannot be parsed as an integer value. The TryParse method is more foregiving
string myString = "7";
if (! int.TryParse(myString, out i))
Log.Debug("That's not an int !");
These methods have overloads which accept info on the format of the string to be parsed. You will really need these when it comes to parsing date values. Alas the overloaded parameters are of somewhat scary types like an IFormatProvider interface.
Far easier to use is the ParseExact method which takes a custom format as parameter. In the text file I had to work through dates were encoded as yyyyMMdd. Instead of working through format providers the ParseExact method accepts this custom format string itself.
try
{
DateTime ingangsDatum = DateTime.ParseExact(msg.Datum_Aanst, "yyyyMMdd", CultureInfo.CurrentCulture);
}
catch (FormatException fex)
{
AfgeKeurd(string.Format("Datum aanstelling {0} niet herkend als geldige datum", msg.Datum_Aanst));
return;
}
Forgive me the double dutch, but the snippet should speak for itself. afaik there is no TryParseExact member, I have to catch a formatexception.
Another error I often see (and make) is using "yyyymmdd" as format string. Which is perfectly valid but it will take the minutes, not the Month.