-1

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.

spc
  • 131
  • 5
  • 19
  • Looks like you want to set a property based on a string, you will need reflection to do this. https://stackoverflow.com/questions/619767/set-object-property-using-reflection – Ryan Thomas Jan 30 '23 at 10:34
  • 2
    You'd better define the properties as an array `public string[] subs;` – shingo Jan 30 '23 at 10:34
  • 1
    Are you really constrained to the C# versions 2-4? JIC - latest one is C# 11. – Guru Stron Jan 30 '23 at 10:40

1 Answers1

1

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";
}
Guru Stron
  • 102,774
  • 10
  • 95
  • 132