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.

5
  • 1
    Refactor to make a collection of values instead. Commented Mar 1, 2012 at 16:44
  • 10
    I suggest you get a good C# book. Commented Mar 1, 2012 at 16:44
  • What about using a list of strings instead? Are you binding these strings? Commented Mar 1, 2012 at 16:44
  • See this stackoverflow.com/a/4637/785966 Commented Mar 1, 2012 at 16:45
  • That doesn't work in compiled languages. Use a List<>. Commented Mar 1, 2012 at 16:45

5 Answers 5

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.)

Sign up to request clarification or add additional context in comments.

2 Comments

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.
@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.
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";
}

Comments

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.

Comments

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>

1 Comment

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.)
0

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

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.