0

I've seen some people use SqlDataReader to get data from database as

reader["Test"].ToString();
...

and others as

reader.GetString(0);
...

Is there any difference in any way? Or does it come down to personal preference?

1
  • 1
    You are better off using the first example when doing this. If column order changes you have alot of potential for error. It is usually best to avoid hard coded indexing at all times. Commented Apr 9, 2015 at 13:45

2 Answers 2

3

Pretty obvious:

  • first one should be used when you know column names of data returned. For me it is preferred to second since column order can be changed. Also in this case you can convert datatype of returned objects later.
  • second one is preferable when you don't know these names (or maybe even columns has no names) but you're ensured in exact datatype of columns you're accessing. If column datatype will be mismatched - you'll get exception. So if you can't access colmn by name and not sure in exact datatype it's better to use GetValue instead of GetString and other typed methods. For me this way of accessing data is really useful only if your query something like 'select x, sum(y) from sometable` - i.e. second column has no name so you can't access it by name.

Considered to performance - accessing by name takes slightly more time since accessing by index internally is

public override object this[int i]
{
    get
    {
        return this.GetValue(i);
    }
}

and accessing by name is

public override object this[string name]
{
    get
    {
        return this.GetValue(this.GetOrdinal(name));
    }
}

So accessing by name invokes GetOrdinal first.

But in real application this difference is absolutely negligable.

Sign up to request clarification or add additional context in comments.

3 Comments

Just another small question how would I read an int value using the first example?
@Code well , for example you can use Convert.ToInt32(reader["Test"]);
Right, Thanks once again :)
0

It always makes sense to use field names instead of indices, because you could get some troubles, if the order of the fields in the SQL statement changes.

I prefer using this way: DataReader.GetString() via columnname

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.