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)