1

Is there a way in c# or VB to dynamically call variables from a loop? Instead of going one by one of every variable?

Imagine the following example,I want to set dog1Legs, dog2Legs, dog3Legs, Is there a way how to call them from a loop?

String dog1Legs;
String dog2Legs;
String dog3Legs;

for(int i=1; i<4; i++)
{

    dog(i)Legs = "test";
}
3
  • 2
    It's called an array of Action<T> if you really want to invoke. Otherwise it's just an array. Commented Apr 27, 2013 at 11:42
  • 1
    This is what arrays are for. Commented Apr 27, 2013 at 11:43
  • I asked same thing today : stackoverflow.com/questions/16249823/… Commented Apr 27, 2013 at 11:45

3 Answers 3

6

You need no write the code as

String dog1Legs;
String dog2Legs;
String dog3Legs;

for (int i=1; i<4; i++)
{
    FieldInfo z = this.GetType().GetField("dog" + i + "Legs");
    object p = (object)this;     
    z.SetValue(p, "test");
}
Sign up to request clarification or add additional context in comments.

1 Comment

While this can work - assuming those are fields, and not local variables - reflection is probably not the best way to handle what he needs here.
3

You should use an array or list. E.g.

var dogLegs = new String[3];

for(int i=0; i<dogLegs.Length; i++)
{
    dogLegs[i] = "test";
}

Or making a Dog class might make sense, e.g.

void Main()
{
    var dogs = new List<Dog>();
    dogs.Add(new Dog { Name = "Max", Breed = "Mutt", Legs = 4 });
    foreach (var dog in dogs)
    {
        // do something
    }
}

class Dog
{
    public int Legs { get; set; }
    public string Breed { get; set; }
    public string Name { get; set; }
}

Comments

1

No, you can't do this. Typical solution is dictionary:

  Dictionary<String, String> dogs = new Dictionary<String, String>();

  dogs.Add("dog1Legs", null);
  dogs.Add("dog2Legs", null);
  dogs.Add("dog3Legs", null);

  for(int i = 1; i < 4; i++) {
    dogs["dogs" + i.ToString() + "Legs"] = "test";
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.