Microsoft Knowledge Base Email Alertz

KBAlertz.com: System.ArgumentException when Calling StringBuilder.Insert Method

Receive Microsoft Knowledge Base articles by E-Mail?

Every night we scan the Microsoft Knowledge Base. If technologies you're interested in are updated, we'll send you an e-mail. You only get one e-mail a day, and only when new articles are added.

Click here to create a
FREE account
Already have an account?
[Click here to Login]

Search KbAlertz

Advanced Search

Webmasters
Put kbAlertz on your website.
[ Click Here for more! ]





ASP.NET 2.0 Web Hosting with SQL 2005: Click Here!
Discount ASP.NET Hosting


Bug Tracking Software
For bug tracking software or defect tracking software or issue tracking software, visit Axosoft.


Community Site



We Send hundreds of thousands of emails using ASP.NET Email



Expert Web Design & Graphic Design
Design44.com




Mentioned In








Microsoft Knowledge Base Article

This article contents is Microsoft Copyrighted material.
©2005-©2007 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks




System.ArgumentException when Calling StringBuilder.Insert Method

Article ID:949175
Last Review:February 14, 2008
Revision:1.2
Source: Microsoft Support

Back to the top

RAPID PUBLISHING

RAPID PUBLISHING ARTICLES PROVIDE INFORMATION DIRECTLY FROM WITHIN THE MICROSOFT SUPPORT ORGANIZATION. THE INFORMATION CONTAINED HEREIN IS CREATED IN RESPONSE TO EMERGING OR UNIQUE TOPICS, OR IS INTENDED SUPPLEMENT OTHER KNOWLEDGE BASE INFORMATION.

Back to the top

Action



You are developing a .NET Framework application using an instance of System.Text.StringBuilder, whose Capacity has been initialized to a specific number of characters. You then call the StringBuilder.Insert method to insert a string at a specified location within range of the Capacity, similar to the code below.

Visual Basic .NET
===============

    Sub Main()
        Dim strTest As New System.Text.StringBuilder(11)
        strTest.Insert(3, "Hello")
        Console.WriteLine(strTest.ToString)
    End Sub


C# .NET
======

    static void Main(string[] args)
        {
            System.Text.StringBuilder strTest = new StringBuilder(11);
            strTest.Insert(3, "Hello");
            Console.WriteLine(strTest.ToString());
        }


 

Back to the top

Result

You receive the following exception and call stack.

System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
   at System.Text.StringBuilder.Insert(Int32 index, String value, Int32 count)
   at ConsoleApplication1.Program.Main(String[] args) 
   at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

Back to the top

Cause

The Index specifed in the Insert method is larger than the current length of the StringBuilder. The Capacity property specifies the maximum number of characters that can be contained within the memory currently allocated by the StringBuilder. It does not initialize the StringBuilder to a particular Length. In the example above, the code is attempting to insert a string at Index 3. Since the StringBuilder does not currently contain any data, you can only insert a string at Index 0.

This behavior is by design.

Back to the top

Resolution

Before calling the Insert method, make sure the StringBuilder's Length property is greater than or equal to the Index you will be using in the Insert method. You can initialize the StringBuilder to contain a sufficient characters in its constructor, or you can use the Append method to add characters to the StringBuilder. For example, the following code add three spaces to the StringBuilder, which will then allow you to begin inserting at Index 3.

Visual Basic .NET
=============

    strTest.Append(" "c,3) 'Append 3 spaces
    strTest.Insert(3, "Hello")

C# .NET
======

    strTest.Append((char)32,3); //Append 3 spaces
    strTest.Insert(3, "Hello");

Back to the top

DISCLAIMER

MICROSOFT AND/OR ITS SUPPLIERS MAKE NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY, RELIABILITY OR ACCURACY OF THE INFORMATION CONTAINED IN THE DOCUMENTS AND RELATED GRAPHICS PUBLISHED ON THIS WEBSITE (THE “MATERIALS”) FOR ANY PURPOSE. THE MATERIALS MAY INCLUDE TECHNICAL INACCURACIES OR TYPOGRAPHICAL ERRORS AND MAY BE REVISED AT ANY TIME WITHOUT NOTICE.

TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, MICROSOFT AND/OR ITS SUPPLIERS DISCLAIM AND EXCLUDE ALL REPRESENTATIONS, WARRANTIES, AND CONDITIONS WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO REPRESENTATIONS, WARRANTIES, OR CONDITIONS OF TITLE, NON INFRINGEMENT, SATISFACTORY CONDITION OR QUALITY, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, WITH RESPECT TO THE MATERIALS.

Back to the top


APPLIES TO
Microsoft .NET Framework 1.1
Microsoft .NET Framework 2.0
Microsoft .NET Framework 3.0
Microsoft .NET Framework 3.5

Back to the top

Keywords: 
kbnomt kbrapidpub KB949175

Back to the top

       

Community Feedback System

Very often, it takes hours to solve a problem. Very often, you've looked high and low, and have tried a lot of solutions. When you finally found it, chances are, it was because someone else helped you. Here's your chance to give back. Use our community feedback tool to let others know what worked for you and what didn't.

Please also understand that the community feedback system is not warranted to be correct, it's simply a system that we've built to let people try and help each other. If something in a feedback response doesn't make sense to you, or you're not comfortable making changes that the feedback talks about (like registry edits), please consult a professional.

Thank you for using kbAlertz.com Feedback System.

-- Scott Cate

Be the first to leave feedback, to help others about this knowledge base article.

(Optional) Name

(Optional) Public URL Or Email

Comments
No HTML -- Text Only Please