The following extension method was set up in some code I maintain.
public static Int32 GetInt32(this System.Data.Common.DbDataReader reader, string name)
{
return reader.GetInt32(reader.GetOrdinal(name));
}
Which is then called like this:
int field1 = dr.GetInt32("field1");
Is this really any better than just casting to an int like this:
int field1 = (int)dr["DiskGroupNum"];
There is a fundamental difference here. In one case you say, “I’m going to just assume this is an int
“, and in the former, you ask the reader to give you an int
. If the value is already an int
, I would not expect any difficulty. However, what happens when the value is a Int64
? You’re casting it to an int
which is only 4 bytes long. You may get unexpected surprises this way if you’re lucky. If you’re not, the program continues like nothing happened, and you wind up with a value missing its upper 4 bytes.
However if you ask the reader to give you an Int32
, you will see it complain should there be some problems with doing so. It might seem contrary writing code to potentially create exceptions, but it works in your favor ultimately, trust me. Even if something does go wrong when you don’t expect it, the error is clear and can be fixed easily.
If you have a value that doesn’t reflect what is read, it may cause problems elsewhere in your program and leave you scratching your head as to why.
3
Actually, I would go with a third option. Retrieve the column ordinal up-front and use the ordinal overloads. In any case where you have multiple rows, it saves work:
var ord_field1 = dr.GetOrdinal("field1");
while(dr.Read())
{
...
var field1 = dr.GetInt32(ord_field1);
...
}
2
No, it is not better than casting to int
(in my opinion).
In your specific example, dr["DiskGroupNum"]
returns type object
, which means that your second example:
int field1 = (int)dr["DiskGroupNum"];
You are actually unboxing the object
to type int
, which will give you an InvalidCastException
if it’s not exactly of type int
(Int32
specifically).
Why I think it is not beneficial to have an extension method to do this is:
- It’s more writing
- It’s more code to debug
- You’ll have to write specific code for different types