none
Handling of Null values while using IDataReader methods RRS feed

  • Question

  • I am providing a wrapper to an IDataReader in one of my applications for some purpose.

    What I need to know is, what is the expected behaviour when a null field is accessed by methods like GetInt16()???

     

    I mean, the Indexer property can return SystemDBNull as it returns an object, but methods like GetInt16() cannot return an object, and there is no logical mapping from Null to Int16.

     

    In that case, should an exception be thrown, or what else???

    Monday, May 26, 2008 8:12 AM

Answers

  • > In that case, should an exception be thrown, or what else???

     

    Yes, you should throw an exception in this case.  The precise type of the exception is not specified by the IDataReader documentation.  As an example, SqlClient throws SqlNullValueException.

     

    Monday, May 26, 2008 2:50 PM

All replies

  • If you call GetInt16() on a filed which contains null value, an exception will be thrown. To avoid it you can check for DBNull before calling GetInt16(). If you have nullable int you can map null to null.

    Monday, May 26, 2008 9:32 AM
  •  Giorgi Dalakishvili wrote:
    If you have nullable int you can map null to null.


    GetInt16() needs to return an Int16, which is a structure type. What do you mean by saying, "Map Null to Null".
    How can an Int16 map to Null, and how can a function that needs to return an Int16 return a Null???
    Monday, May 26, 2008 10:28 AM
  • > In that case, should an exception be thrown, or what else???

     

    Yes, you should throw an exception in this case.  The precise type of the exception is not specified by the IDataReader documentation.  As an example, SqlClient throws SqlNullValueException.

     

    Monday, May 26, 2008 2:50 PM
  • Ever heard about Nullable Types ?
    Monday, May 26, 2008 4:55 PM
  • IDataRecord.GetInt16 does not return a Nullable<int>, so nullable types are not relevant here.

    Monday, May 26, 2008 5:01 PM
  • He is writing wrapper for IDatareader so he can use nullable tyupes to retun null when the data is DBNull.
    Monday, May 26, 2008 5:07 PM
  • Well, never heard of Nullable types before. Sure, they are a handy tool to have...
    Well, they are not suitable for implementation currently as majority of code already relies on Exception being thrown, when a Null value is retrieved from a DataReader by casting it to some form.

    However, when writing clean code next time, they would come handy. Thanx!!!
    Tuesday, May 27, 2008 2:17 PM