2

Closed

Bug in StringBuilder Append(char[] value, int startIndex, int charCount)

description

I have found a bug in StringBuilder v4.2
 
 
var builder = new StringBuilder();
builder.Append(new[] {'A', 'B', 'C'}, 1, 2);
 
builder should hold the string "BC" but it only holds "B".
Closed Jul 23, 2012 at 10:40 PM by ZachLibby
Fixed in code change set 23510.

comments

juliusfriedman wrote May 25, 2012 at 4:35 PM

I will take a look and add an additional Unit Test if warranted. Thanks for the info.

juliusfriedman wrote May 25, 2012 at 4:47 PM

if (charCount != 0)
        {
            char[] tmp = new char[ charCount ];
            System.Array.Copy(value, startIndex, tmp , 0, charCount);
            this.Append(tmp, 1);
        }
Should be:

if (charCount != 0)
        {
            char[] tmp = new char[ charCount ];
            System.Array.Copy(value, startIndex, tmp , 0, charCount);
            this.Append(tmp, tmp.Length);
        }
Thats a my bad :p

juliusfriedman wrote May 25, 2012 at 5:15 PM

I have emailed Lorenzo the fix and the new Unit Test... Thank you for the info again! If you have any other problems let me know...

juliusfriedman wrote May 25, 2012 at 5:15 PM

and yea, tmp.Length could probably be charCount :p

juliusfriedman wrote May 25, 2012 at 5:19 PM

And actually I was wrong... It was missing a for... but I have still fixed it..
            char[] tmp = new char[ charCount ];
            System.Array.Copy(value, startIndex, tmp , 0, charCount);
            foreach(char c in tmp) this.Append(c, 1)
Thanks again...

juliusfriedman wrote May 25, 2012 at 5:22 PM

Full method:

public StringBuilder Append(char[] value, int startIndex, int charCount)
    {
        if (startIndex < 0)
        {
            throw new ArgumentOutOfRangeException("startIndex");
        }
        if (charCount < 0)
        {
            throw new ArgumentOutOfRangeException("count");
        }
        if (value == null)
        {
            if ((startIndex != 0) || (charCount != 0))
            {
                throw new ArgumentNullException("value");
            }
            return this;
        }
        if (charCount > (value.Length - startIndex))
        {
            throw new ArgumentOutOfRangeException("count");
        }
        if (charCount != 0)
        {
            char[] tmp = new char[ charCount ];
            System.Array.Copy(value, startIndex, tmp , 0, charCount);
            foreach(char c in tmp) this.Append(c, 1);
        }
        return this;
    }