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 3.5 Web Hosting with Windows 2008 and SQL 2008: Click Here!
Discount ASP.NET Hosting
ASP.NET 2.0 and 3.5
Windows2008 and SQL2008
US and UK Hosting
KBAlertz referrals get
** SIX MONTHS FREE **


Community Site



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


ASP.NET 3.5 Web Hosting with Windows 2008 and SQL 2008: Click Here!
Discount ASP.NET Hosting
ASP.NET 2.0 and 3.5
Windows2008 and SQL2008
US and UK Hosting
KBAlertz referrals get
** SIX MONTHS FREE **




Mentioned In








Microsoft Knowledge Base Article

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




Article ID: 949175 - Last Review: February 14, 2008 - Revision: 1.2

System.ArgumentException when Calling StringBuilder.Insert Method

Source: Microsoft Support

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.

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());
        }


 

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()

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.

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");

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.

APPLIES TO
  • Microsoft .NET Framework 1.1
  • Microsoft .NET Framework 2.0
  • Microsoft .NET Framework 3.0
  • Microsoft .NET Framework 3.5
Keywords: 
kbnomt kbrapidpub KB949175
       

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

Bernardo Rosmaninho - bernardo.rosmaninho NOSPAM-AT-NOSPAM gmail.com Report As Irrelevant  
Written: 5/8/2009 1:03 PM
Very nice tip. It was exactally what i had to did. Ty.

(Optional) Name

(Optional) Public URL Or Email

Comments
No HTML -- Text Only Please