0

I have a number of variables named test1....test10 they are all declared as a string.

what I want to do is access them from inside a loop using the loop counter something like this:

string test1;
//...
string test10;

for (int i = 1; i < 10; i++)
{
    test + i.ToString() = "some text";  
} 

any idea how I could do this? this is a WPF .net 4 windows App.

RTFS
  • 115
  • 1
  • 10

5 Answers5

10

Simple answer: don't have 10 variables, have one variable which is a collection:

List<string> test = new List<string>();
for (int i = 1; i < 10; i++)
{
    test.Add("some text");
}

Having lots of variables which logically form a collection is a design smell.

(If you really have to do this, you could use reflection. But please don't.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • I'm wondering why you are getting more and more reputation while my answer is posted at the same time. Must have something to do with the herd instinct. – Felix K. Mar 01 '12 at 16:53
  • 3
    @FelixK.: On the contrary, this answer has gained me precisely 0 reputation :) More seriously, there may be part herd instinct and part due to bringing up the fact that it's a design problem. – Jon Skeet Mar 01 '12 at 16:56
4

You simply can't, use a List or a String-Array for this purpose.

List

List<String> myStrings = new List<String>();
for (Int32 i = 0; i < 10; i++) 
{
    myStrings.Add("some text");
}

String-Array

String[] myStrings = new String[10];
for (Int32 i = 0; i < myStrings.length; i++) 
{
    myStrings[i] = "some text";
}
Felix K.
  • 6,201
  • 2
  • 38
  • 71
2

Try adding them to an array of string[] or simply create a List<string> list = new List<string>();.

With the list, you can iterate easily.

0

This is not really possible, unless you use the dynamic keyword, and then you will get a property instead of a true variable. Take a look at ExpandoObject, it will allow you to add properties based on a string variable.

In your case, as other have said, you really should use a List<string>

Dervall
  • 5,736
  • 3
  • 25
  • 48
  • Pointing out dynamic or ExpandoObject to an obvious beginner is like giving them a big red button and then saying they shouldn't push it. (I'm not downvoting, because it's technically correct, but still.) – Servy Mar 01 '12 at 17:16
0

For something as simple as 10 items, an array is the best way to go. Fast and easy.

Aaron Deming
  • 1,015
  • 10
  • 12