Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to do this: Convert.IsDBNull(row[somecolumn]) checking

Tags:

c#

ado.net

Is there a better way to write this code..

MyObject pymt = new MyObject();
pymt.xcol1id= Convert.IsDBNull(row["col1id"]) ? 0 : (int)row["col1id"];
pymt.xcold2id= Convert.IsDBNull(row["col2id"]) ? String.Empty : (string)row["col2id"];
pymt.xcold3id = Convert.IsDBNull(row["CustNum"]) ? 0 : (decimal)row["xcold3id"];

could this be done in a cleaner way .. like generic methods etc??

like image 443
dotnet-practitioner Avatar asked Aug 24 '09 20:08

dotnet-practitioner


1 Answers

You could make generic extension methods like this:

public static class DataRowExtensions {

   public static T GetValueOrDefault<T>(this DataRow row, string key) {
      return row.GetValueOrDefault(key, default(T));
   }

   public static T GetValueOrDefault<T>(this DataRow row, string key, T defaultValue) {
      if (row.IsNull(key)) {
         return defaultValue;
      } else {
         return (T)row[key];
      }
   }

}

Usage:

MyObject pymt = new MyObject();
pymt.xcol1id = row.GetValueOrDefault<int>("col1id");
pymt.xcold2id = row.GetValueOrDefault<string>("col2id", String.Empty);
pymt.xcold3id = row.GetValueOrDefault<int>("CustNum"]);
like image 82
Guffa Avatar answered Sep 21 '22 13:09

Guffa