Let’s say I have a class like this:
class Person
{
public string name;
public string address;
public string city;
public string state;
public string zip;
}
And I’m performing a data dip on a database:
Select Name, Address, City, State, Zip
FROM Persons_Tbl
Currently, I am storing the data in the class like this:
// Person class and SqlDataReader have been instantiated.
while (reader.Read())
{
p.name = reader[0].ToString();
p.address = reader[1].ToString();
p.city = reader[2].ToString();
p.state = reader[3].ToString();
p.zip = reader[4].ToString();
}
This is just an example. In reality, I have more columns to retrieve. Rather than writing one line for each column data dip, I’d like to make the code smaller and loop, via an index. This is possible using the reader object, since I can retrieve columns via an index.
However, is it possible to index class member variables in the same manner? Here is the rewritten while loop, to better explain what I am asking:
// pseudocode!
while (reader.Read())
{
for (int index = 0; index < 5; index++)
{
index of p member variables (i.e. name, address) = reader[index].ToString();
}
}
Is it possible to manipulate class member variables in this manner? Or, must I create a member variable that is an array type? I’d prefer to write out each member variable of the Person class, since it looks cleaner and is easier to read.
Thank you very much, in advance.
Yes, you can do something like that.
Example:
What you use here is called Indexers in
C#.after can use it like:
Even considering this, may be, original way to resolve this problem, I would first think about possible ways re-architecting the code to avoid this type of solutions.