0

I am trying to use a string to identify my array. I have a method that takes in the string as a parameter and I wanted to use the value of that string to identify which array to edit.

class Test{

    static string[] myNums = { "1","2","3","4" };
    static string[] myNames = { "Bill", "Peter", "Michael", "Samir" };

    public Test
    {
        int choice = Int32.Parse(Console.ReadLine()); 

        if(choice == 1)
           ProcessAccount("myNums");
        else if(choice == 2)
           ProcessAccount("myNames");
    }

    public void ProcessAccount(string id)
    {
        //This is where I want to identify the array to modify
        //based on the ID so I do not have to do separate lines of code
        id[0] = "PAST DUE"; //something like this
    }

}

Is there any way to do this?

Hermes Trismegistus
  • 515
  • 2
  • 5
  • 16
  • 3
    There are multiple different ways you could approach this, but honestly this is typically a bad idea and your question sounds like an XY problem. Can you provide more detail to why you think you need to do this? – maccettura Mar 08 '18 at 04:03
  • yes i'll reformat – Hermes Trismegistus Mar 08 '18 at 04:04
  • No it's not possible to reference local variables dynamically using strings. You can use reflection to reference class members by string name, but not local variables. – D Stanley Mar 08 '18 at 04:05
  • I dont think its possible – Agent_Orange Mar 08 '18 at 04:10
  • Can't you just pass the array itself into `ProcessAccount`? Something like `void ProcessAccount(string[] arr) { ...` – caesay Mar 08 '18 at 04:26
  • 1
    Seems like you should make classes that represent your data. It’s still unclear though. Why would you override the first index of the array? – maccettura Mar 08 '18 at 04:39
  • @caesay is right. What's the point of using a number to choose a `string` and then using that `string` to choose an array when you can just use the number to choose the array in the first place? – jmcilhinney Mar 08 '18 at 04:41

0 Answers0