0

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()));
}
3
  • 1
    What is that supposed to show? Are you trying to print i followed by myObj[i]? Commented Sep 16, 2016 at 17:24
  • i am trying to generate a fixed width file. i is the index or columns of the array object Commented Sep 16, 2016 at 17:42
  • This is going to crash because <= should be != or <. Commented Sep 16, 2016 at 17:57

1 Answer 1

4

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));
Sign up to request clarification or add additional context in comments.

3 Comments

There is no need to call ToString() on myObj[i] as it is called by default
@Luiso Technically calling ToString() on a value type (if the parameters are value types) will prevent the boxing that would occur prior to ToStringing the value, and could potentially affect performance slightly (negligible, but still technically not equivalent). I agree though, that personally I would remove ToString().
The problem using PadLeft/PadRight is that , the last coulmn i need to fill with a blank space of 100 and it is not taking the 100 spaces ,wheres as just taking 8 spaces .

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.