2
Answers

NP130 StringBuilder

Maha

Maha

16y
1.6k
1

Hi Guys

 

NP130 StringBuilder

 

In the following program Console.WriteLine() method (highlighted in yellow) is only giving 'test' output, one can say because sb.Length = 4; method is giving truncated output.    

 

But in the next step output even though sb.Length = 20; Console.WriteLine() method (highlighted in blue) is only giving 'test           ' output. Why is it truncating the string?   

 

Please explain the reason.

 

Thank you

 

using System;

using System.Text;

 

class MainClass

{

    public static void Main()

    {

        StringBuilder sb = new StringBuilder("test string");

        int length = 0;

 

        length = sb.Length;

        Console.WriteLine("The result is: '{0}'", sb);

        Console.WriteLine("The length is: {0}", length);

 

        sb.Length = 4;

        length = sb.Length;

        Console.WriteLine("The result is: '{0}'", sb);

        Console.WriteLine("The length is: {0}", length);

 

        sb.Length = 20;

        length = sb.Length;

        Console.WriteLine("The result is: '{0}'", sb);

        Console.WriteLine("The length is: {0}", length);

    }

}

/*

The result is: 'test string'

The length is: 11

The result is: 'test'

The length is: 4

The result is: 'test                '

The length is: 20

*/

Answers (2)
0
Maha

Maha

NA 0 173.3k 16y

Thank you very much for explanation.

0
Ryan Alford

Ryan Alford

NA 2.3k 891.7k 16y
when you set the StringBuilder to "test string", it's length is 11.  When you set the length to 4, you are truncating the StringBuilder object to a length of 4.  Therefore, all of the characters after the 4th position are gone.  Just because you set it's length to 20 doesn't mean the original string will magically appear again.  The StringBuilder object is "test" after you set it's length to 4, and the rest of the string is lost forever.