TRA
TRA

Reputation: 45

How to use variable inside String.Format

I want to use String.Format inside the loop, but it does not allowing me to define a variable i inside the String.Format. Here is my code

StringBuilder Sb;
for(i=0 ;i<=myObj.length;i++)
{
    Sb=Sb.Append(String.Format("{i,5}",myObj[i].Tostring()));
}

Upvotes: 0

Views: 193

Answers (1)

Joe Enos
Joe Enos

Reputation: 40393

To use it in the Format method, you use numbers corresponding to the indexes of the params array.

Also, don't reassign Sb, just call Append or AppendFormat:

Sb.Append(String.Format("{0,5}", myObj[i].ToString()));
//or
Sb.AppendFormat("{0,5}", myObj[i].ToString());

If you're fortunate enough to be on the latest and greatest C# version, you can skip Format and do it with the new string interpolation syntax:

Sp.Append($"{myObj[i],5}");

Or since all you're doing is padding, then you can also do:

Sb.Append(myObj[i].ToString().PadLeft(5));

Upvotes: 4

Related Questions