CodeSOD: A Long Conversion

This post was originally published on this site

The Daily WTF

Let’s talk a little bit about .NET’s TryParse method. Many types, especially the built in numerics, support it, alongside a Parse. The key difference between Parse and TryParse is that TryParse bakes the exception handling logic in it. Instead of using exceptions to tell you if it can parse or not, it returns a boolean value, instead.

If, for example, you wanted to take an input, and either store it as an integer in a database, or store a null, you might do something like this:

int result; if (int.TryParse(data, out result)) { rowData[column] = result; } else { rowData[column] = DBNull.Value; }

There are certainly better, cleaner ways to handle this. Russell F. has a co-worker that has a much uglier way to handle this.

private void BuildIntColumns(string data, DataRow rowData, int startIndex, int length, string columnName, FileInfo file, string tableName) { if (data.Trim().Length > startIndex)

To read the full article click on the 'post' link at the top.