3

I was wondering whether there's a way in a "for" loop to assign a value to a string variable named according to its index number?

let's say I have 3 string variables called:

string message1 = null;
string message2 = null; 
string message3 = null;

And I want the 'for' loop to do the something like the following code:

 for (int i = 1; i <=3; i++)
 {
   messagei = "blabla" + i.ToString();
 }

I don't want to use an "if" or a "switch" because it will make the code harder to follow.

Is there a way to do that?

4
  • 3
    Yup, it's possible. You call it an array. Commented Dec 27, 2011 at 15:01
  • messagei is the name of an undeclared variable. You don't have dynamic variable names in C#. Commented Dec 27, 2011 at 15:01
  • possible duplicate of Declaring variable dynamically in VB.net Commented Dec 27, 2011 at 15:02
  • You have got many alternates to achieve that. But the question (For you) is, what does your business demand? It might be perfect in your case to give appropriate names to each variable and store appropriate value in that variable by reading the respective index. Simple code should always be given priority over using a fancy API(for instance, reflection) Commented Dec 27, 2011 at 16:04

9 Answers 9

13

You don't want 3 variables with the same name, you want an array of those variables.

string[] messages = new string[3]; // 3 item array

You can then store your items in the array elements

messages[0] = "Apple"; // array index starts at 0!
messages[1] = "Banana";
messages[2] = "Cherry"; 

Another way to create that array is an inline array initializer, saves some code

string[] messages = { "Apple", "Banana", "Cherry" }; 

(Note: there are more valid syntaxes for array initialization. Research on the various other methods is left as an exercise.)

And access them via a loop (foreach)

foreach (string fruit in messages)
{
    Console.WriteLine("I'm eating a " + fruit);
}

Or for

for (int i = 0; i < messages.Length; i++)
{
    Console.WriteLine("I'm eating a " + messages[i]); // reading the value
    messages[i] = "blabla" + i.ToString(); // writing a value to the array
}
Sign up to request clarification or add additional context in comments.

1 Comment

And then ofcourse use messages[i] = "blabla" + i.ToString(); +1 for a correct direction
2

can you use an array? or list type?

string[] messages = new string[3];
for (int i = 1; i <=3; i++)
 {
   messages[i] = "blabla" + i.ToString();
 }

Comments

1

You said you don't want to have a switch statement. I realize this does have a switch, but if you must have three different variables, you could encapsulate your switch inside a function call:

string message1 = null;
string message2 = null; 
string message3 = null;

void SetMessage(int i, string value)
{
    if(i == 1)
        message1 = value;
    etc
}

 for (int i = 1; i <=3; i++)
 {
   SetMessage(i, "blabla" + i.ToString());
 }

Not an optimal solution but if you MUST have separate variables it will hide the mess.

Comments

0

You can't do that (well, not sanely). Have you considered using an array of strings instead?

Comments

0

I think you should use an array for this kind of variables.

string[] message = new string[3];
for (int i = 1; i <=3; i++)
{
     message[i] = "blabla" + i.ToString();
}

Comments

0

Usually instead of having N differents variables named 1, 2, ..., N the way is to store them in an array:

string message[3];
message[0] = null;
message[1] = null;
message[2] = null; 

and then the loop:

for (int i = 0; i <=2; i++)  
{  
   message[i] = "blabla" + i.ToString();  
}  

Note that, usually again, a set of indexed variables starts with value 0 ;)

Comments

0

I would go about it a little differently, maybe use a dictionary and store your messages. Something like this:

 Dictionary<string, string> messages = new Dictionary<string, string>();
 for(int i = 1; i <= 3; i++)
 {
      messages.Add("message" + i.ToString(), i.ToString());
 }

Comments

0

You can also do it without the index:

    string[] Messages = { "Tom", "Dick", "Harry" };

    foreach (String Message in Messages)
    {
        Response.Write("Hello " + Message + "<br />");
    }

Comments

-1

If you declare your variable in a class as public variables, you can access them as follow;

public partial class _Default : System.Web.UI.Page
{
    public string message1 = null;
    public string message2 = null; 
    public string message3 = null;


    public void setVars()
    {
        for (int i = 1; i <=3; i++)
         {
             this.GetType().GetField("message" + i.ToString()).SetValue(this, "blabla" + i.ToString());

         }
    }




}

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.