I have seen different ways to retrieve a string field from SQL. Is there a "right" way, and what are the differences
SqlDataReader rdr;
1. String field = (String) rdr["field"];
2. String field = rdr["field"].ToString();
3. String field = rdr["field"] As String;
Thanks!
You could also use:
int ordinal=rdr.GetOrdinal("stringField");
if (rdr.IsDBNull(ordinal))
{
return string.Empty; //Or null or however you want to handle it
}
else
{
rdr.GetString(ordinal);
}
Which if you look at the definition for SQlDataReader["field"] looks like:
public override object this[string name]
{
get
{
return this.GetValue(this.GetOrdinal(name));
}
}
Essentially this is doing the same thing, only it's type safe. What I like to do is Create my own IDataReader which wraps SqlDataReader. CSLA uses a simillar mechanism that they call SafeDataReader since it provides overloads for all the various data types which implements this pattern.
If you know the field won't be null you could leave out the isDbNull checks. Due to the verbosity I'd recommend putting this in some type of wrapper or helper class and make functions out of them.
So, to be on the safe side - I would choose 3.
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