Is it possible to refer to member variables of a class using an index in C #?

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 am doing data analysis in the database:

 Select Name, Address, City, State, Zip FROM Persons_Tbl 

I am currently storing data in a class as follows:

 // 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. I actually have more columns to retrieve. Instead of writing one row for each drop of column data, I would like to make the code smaller and loop through the index. This is possible with a reader object, since I can get columns using an index.

However, is it possible to index class member variables in the same way? Here is a rewritten while loop to better explain what I'm asking:

 // pseudocode! while (reader.Read()) { for (int index = 0; index < 5; index++) { index of p member variables (ie name, address) = reader[index].ToString(); } } 

Is it possible to manipulate class member variables this way? Or should I create a member variable that is an array type? I would prefer to write each member variable of the Person class, as it looks cleaner and easier to read.

Thanks in advance.

+4
source share
1 answer

Yes, you can do something like that.

Example:

 class Person { public string name; public string address; public string city; public string state; public string zip; public string this[int index] { //SPECIAL PROPERTY INDEXERS get { if(index == 0) return name; else if(index == 1) return address; ... } set { if(index == 0) name = value; else if(index == 1) address = value; ... } } } 

What you use here is called Indexers in C# .

after that you can use:

 Person person = new Person(); person[0] = "James Bond"; //SET NAME person[1] = "London"; //SET ADDRESS ..... 

Even considering this, perhaps an original way to solve this problem, I would first think about possible ways to re-design the code to avoid this kind of solution.

+6
source

All Articles