Search code examples
c#parsingexceptionstring-parsing

can storing data in a database sometimes lead to corrupted data?


I have a field that's stored in the database as a string. It's actually a comma-separated string of numbers that I convert to a list of longs. The lines of code that do the conversion look somewhat like this:

TheListOfLongs = (from string s in StringFromDB.Split(',') 
                  select Convert.ToInt64(s)).ToList<long>();

The code that creates the database storage string looks like this:

return String.Join(",", TheListOfLongs.Select(x=> x.ToString()).ToArray());

This works fine but as you can see, if for some reason there's a problem with the string, the code in the first line of code breaks on Convert.ToInt64(s).

Now I know I can wrap all this around a try statement but my question is this: can storing and retrieving a string in the database corrupt the string (in which case I definitely need the try statement) or is this a one a trillion odd type of event?


Solution

  • I wouldn't worry about corrupt data per se. However, you definitely need to handle the more general case where you can't parse what should be numeric data.

    Even in the most controlled situations it is good programming practice to provide conditions for when you can't process data as you're expecting to be able to. What that means to your application is something you'll need to decide. Wrapping the statement with a try..catch will prevent your application from choking, but may not be appropriate if the parsed list is critical later on.