My suggestion is to never convert ToString when the data is not a string, and if the data is already a string, then calling ToString is redundant, and casting is required for everyone.
I am assuming that the data type in the database is an integer, in which case you can use a nullable int.
int? accountNumber = reader["Account Number"] == DBNull.Value ? null : (int?)reader["Account Number"];
I made an extension method to do just this thing.
public static class SqlDataReaderExtensions { public static T Field<T>(this SqlDataReader reader, string columnName) { object obj = reader[columnName]; if (obj == null) { throw new IndexOutOfRangeException( string.Format( "reader does not contain column: {0}", columnName ) ); } if (obj is DBNull) { obj = null; } return (T)obj; } }
Using
int? accountType = reader.Field<int?>("Account Number");
Matthew
source share