Click here to Skip to main content
15,891,657 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi
how should i do this work?

C#
string s1;
string s2;
string s3;


i want to define variable inside of loop:

C#
for (i=1;i=3;i++)
{
   string s+i.tostring();
}


but s+i.tostring() is wrong.

thanks

What I have tried:

i don't know what should i do

help
Posted
Updated 19-Feb-19 20:15pm
v2

It goes like this:
for (var i = 1; i <= 3; i++)
{
    var myString = "s" + i;
}
 
Share this answer
 
TheRealSteveJudge is right, but ... the whole loop is pointless as shown as the variable will go out of scope at the end of the loop and will be thrown away.

A better solution would be this:
C#
string s = "";
for (int i = 1; i <= 3; i++)
   {
   s = s + i.ToString();
   }
Console.WriteLine(s);
Or for larger loops:
C#
StringBuilder sb = "";
for (int i = 1; i <= 3; i++)
   {
   sb.Append(i.ToString());
   }
Console.WriteLine(sb.ToString());
As strings are immutable - when you concatenate strings you create a new string and have to copy all the info across - it can get incredibly inefficient in terms of processor power and memory if you aren't careful. The StringBuilder class reduces that to a minimum by being an expandable string.
 
Share this answer
 
v2
Comments
TheRealSteveJudge 20-Feb-19 2:45am    
You're right with
the variable will go out of scope

But it is nearly impossible to provide a perfect answer to such a poor question.
The StringBuilder hint is valuable though. 5*
If you're trying to define some string variables named s1, s2, and s3, that's not going to work. You cannot define variable names like that at runtime.

You can define a collection that will hold strings, for example:
C#
List<string> myStrings = new List<string>();
myStrings.Add("some string content");

or an array of strings:
C#
string[] myStrings = new string[3];
myStrings[0] = "some string content";

There's variety of ways of holding a collection of items. You don't normally define a single variable for each item.
 
Share this answer
 
v2
Comments
Bryian Tan 19-Feb-19 14:16pm    
I agreed with you, I think you read his mind. Dangerous :)+5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900