Search code examples
c#.netobjectunboxing

Best way to convert object typed data to value type


I was tasked to create code that would fetch data from database using data reader and I'm curious of what is going to be the best practice between the 3 methods that I could use below to convert data from my data reader which by default fetched with a type of object.

    internal static RoomType SelectRoomType(int roomTypeID)
    {
        SqlCommand commRoomTypeSelector = ConnectionManager.MainConnection.CreateCommand();
        commRoomTypeSelector.CommandType = CommandType.StoredProcedure;
        commRoomTypeSelector.CommandText = "Rooms.asp_RMS_RoomType_Select";
        commRoomTypeSelector.Parameters.AddWithValue("RoomTypeID", roomTypeID);

        SqlDataReader dreadRoomType = commRoomTypeSelector.ExecuteReader();
        if (dreadRoomType.FieldCount != 0)
        {
            dreadRoomType.Read();
            RoomType roomType = new RoomType();
            roomType.RoomTypeID = (int)dreadRoomType["RoomTypeID"];
            roomType.RoomTypeName = (string)dreadRoomType["RoomType"];
            roomType.IsActive = ((string)dreadRoomType["IsActive"]).ToUpper() == "Y";
            roomType.LastEditDate = (string)dreadRoomType["LastEditDate"] != string.Empty ? DateTime.Parse((string)dreadRoomType["LastEditDate"]) : DateTime.MinValue;
            roomType.LastEditUser = (string)dreadRoomType["LastEditUser"];
            dreadRoomType.Close();
            return roomType;
        }
        dreadRoomType.Close();
        return null;
    }

What confuses me here is the unboxing part, According to http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx Boxing and Unboxing is quite expensive and should be avoided. I know that i could use

   int.Parse(dreadRoomType["RoomTypeID"].ToString())

instead of

   roomType.RoomTypeID = (int)dreadRoomType["RoomTypeID"];

The question is are there still ways of converting this data in a much more efficient way that both of this option and if there are no possible ways which of the two ways do you prefer to use. Thanks in advance all help and suggestions are accepted :)


Solution

  • You can use SqlDataReader.GetInt32() to avoid having to convert/parse to int again, for this you do have to know at what index the integer is within the columns selected though:

    roomType.RoomTypeID = dreadRoomType.GetInt32(0);