简体   繁体   中英

Concatenate properties with index in c#

I have a class Student with properties sub1,sub2, and sub3.

I want to access those properties using a loop by concatenating the property name with an index in order to avoid duplication. I tried below code

public class SampleApplication
{
  public static void Main(string[] args)
  {
    Student s =new Student();
    for(int i=1;i<=3;i++)
    {
      s.$"sub{i}"="Subjects";
    }
  }
}

public class Student
{
 public string sub1;
 public string sub2;
 public string sub3;  
}

But I am getting an error like the identifier expected. Can anyone help me to solve this? Thanks in advance.

You need either use reflection or define an indexer:

public class Student
{
    public string sub1;
    public string sub2;
    public string sub3;

    public string this[int index]
    {
        get => index switch
        {
            1 => sub1,
            2 => sub2,
            3 => sub3,
            _ => throw new ArgumentOutOfRangeException()
        };

        set
        {
            switch (index)
            {
                case 1:
                    sub1 = value;
                    break;
                case 2:
                    sub2 = value;
                    break;
                case 3:
                    sub3 = value;
                    break;
                default: throw new ArgumentOutOfRangeException();
            }
        }
    }
}

And usage:

Student s = new Student();
for (int i = 1; i <= 3; i++)
{
     s[i] = "Subjects";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM