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??
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"]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With