1

It might sound kiddish or silly but i wanna know that in codes like..

SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
rdr.Read();
Response.Write(rdr[1]. ToString());

how do we use the SqlDataReader object as an array (rdr[1]) without declaration?

What I want to know is, what is happening in the following line?

Response.Write(rdr[1].ToString());

Since rdr is an object, how art we able to use square brackets with that?

3 Answers 3

1

You are looking for Indexers.

Please refer to this link.

Indexers are a syntactic convenience that enable you to create a class, struct, or interface that client applications can access just as an array

ref: http://msdn.microsoft.com/en-us/library/2549tw02.aspx

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

Comments

0

you can do something like this.

 Object[] values = new Object[reader.FieldCount];
int fieldCount = reader.GetValues(values);

Console.WriteLine("reader.GetValues retrieved {0} columns.",
    fieldCount);
for (int i = 0; i < fieldCount; i++)
    Console.WriteLine(values[i]);

Console.WriteLine();

Comments

0

No, since SqlDataReader is a forward-only read-only stream of rows from a SQL Server database, the stream of rows will be looped through whether explicitly in your code or hidden in a framework implementation (such as DataTable's Load method). So you cannot directly convert it to array type. You need to convert it to list.

It sounds like using a generic list and then returning the list as an array would be a good option. For example,

List list = new List();

while (rdr.Read())
{
     list.Add(rdr.GetInt32(0));
}    

return list.ToArray();

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.