0

I have this class:

public class City
{
    public string city;
    public float residence;
    public float industry;
    public float trade;
    public float total;
}

I want to access to the rows with foreach loop:

List<City> cities = new List<City>();
string[] rows = {"city", "residence", "industry", "trade", "total"};

foreach(string x in rows)
{
    Debug.Log(cities[5].x); // this doesn't work
}

cities[5].residence or cities[5].total works but i don't want to write it directly.

I want to reference to residence or industry like cities[3].x How can I make it work this way?

Abdul Rauf
  • 5,798
  • 5
  • 50
  • 70

1 Answers1

1

Since you are using C#, which is object-oriented programming, I foster you to improve the encapsulation in your code: think behavior rather than data.

This means that City's can be improved toward this goal in this manner:

public sealed class City
{
    private readonly string city;
    private readonly float residence;
    private readonly float industry;
    private readonly float trade;
    private readonly float total;

    public City(string city, float residence, float industry, float trade, float total)
    {
        this.city = city;
        this.residence = residence;
        this.industry = industry;
        this.trade = trade;
        this.total = total;
    }

    public IEnumerable<string> YieldProperties()
    {
        yield return city;
        yield return residence.ToString("R");
        yield return industry.ToString("R");
        yield return trade.ToString("R");
        yield return total.ToString("R");
    }
}

And usage becomes

List<City> cities = new List<City>();
foreach(string p in cities[5].YieldProperties())
{
    Debug.Log(p);
}

So what did I change ?

  • I properly encapsulated the class fields to avoid them leaking outside (which decrease your code maintainability)
  • I provided instead a behavior: the capability to yield itself each element one by one as a string
  • I used sealed and readonly to make the class immutable (which is a good practice for maintainability)
  • I removed the obsolete variable rows which is very dangerous: renaming a field in City would break your code if you forgot to update rows content
  • I didn't use any reflection, which I believe should be avoided as much as possible
Spotted
  • 4,021
  • 17
  • 33