Using String Insert Effectively In C#

String Insert Banner Image

Introduction

Insert is a quick way to put one string into another. In C#, this is good for string manipulation, output variables into strings, or combining strings. But there is an exception that can be raised with incorrect values. There are multiple ways of doing this including, replace, format, concatenation, and Interpolation so keep in mind that C# has multiple ways of doing the same way. Also, I'll explain how insert works, and the interworkings of how it can be done.

What is String Insert?

The insert method puts a single string in-between a section of the string. The first parameter is an index, it lets you pick at what point to insert a string. the second parameter is the string you want to insert. Both of these parameters must be valid input. The size of the string you want o insert doesn't matter just as long as it is inserted in the valid range of the existing string. Syntax

Syntax
public string Insert(int index, string value)

Notice that the function call allows for an index of the current string where the insert will start. Then in the next parameter, you can pass the string you want to insert. Let's see an example, by looking at the code below.

string debugStatement = "Error Generated at  for function";//Starting string
DateTime timestamp = DateTime.Now;//Date that we want to insert
int index = 19;//Start index of the insert
string completedStatement = debugStatement.Insert(index, timestamp.ToString()); //Call the insert function
Console.WriteLine(completedStatement);//Display result
Code Output
    Error Generated at 5/1/2022 2:15:46 PM  for function

This code snippet simply takes an existing string and inserts a date between the at and for text.

String Insert Exceptions

It's important to note when exceptions can happen and when they might happen so that we can guard the code against such cases. The first is the index out-of-range exception.

Index Out of Range Exception

This exception comes when the index provided is either less than 0 or greater than the length of the original string. See the code example below that will generate an error.

string debugStatement = "Error Generated at  for function";//Starting string
DateTime timestamp = DateTime.Now;//Date that we want to insert
int index = -1;//Start index of the insert which will cause an exception
string completedStatement = debugStatement.Insert(index2, timestamp.ToString());//Call the insert function
Console.WriteLine(completedStatement);//Display result

Result

Argument Out of Range Exception Image

As you can see the index is less than 0 which is not a valid index in the original string. To handle this case will have a wrapper function over the string insert method to handle such cases. Check out the code below.

//Protection Against String Insert Index Out of Range Exception
string debugStatement = "Error Generated at  for function";//Starting string//Starting string
DateTime timestamp = DateTime.Now;//Date that we want to insert
int index = -1;//Start index of the insert which will cause an exception
string completedStatement = InsertText(index, debugStatement, timestamp.ToString());//Call the updated insert function
Console.WriteLine("Result1:" + completedStatement);//Display result

index = 100;//Start index that is outside the length of the original string
completedStatement = InsertText(index, debugStatement, timestamp.ToString());//Call the updated insert function
Console.WriteLine("Result2:" + completedStatement);//Display result

string InsertText(int index, string originalText, string textToInsert)
{
    if (index < 0 || index > originalText.Length - 1)
    {
        return originalText;
    }
    string newText = originalText.Insert(index, textToInsert);
    return newText;
}

In the insert text wrapper function we handle both the case of the index being less than 0 and also when the insert index is greater than the length - 1 of the original string.

Null Exception

Null Exception happens when the string we want to insert is null. If it was just an empty string it would be ok and there wouldn't be an exception so we must guard the code against a null value. See the code below to see how the error can be caused.

string debugStatement = "Error Generated at  for function";//Starting string
string? timestamp = null;//Date that we want to insert but since it is null an exception will be thrown
int index = 19;//Start index of the insert which will cause an exception
string completedStatement = debugStatement.Insert(index, timestamp);//Call the updated insert function
Console.WriteLine(completedStatement);//Display result

Result

ArgumentNull Exception Image

To resolve this issue. We are going to add a null check to that parameter so that use case will be handled. Now adding that check to the preview created InsertText wrapper function. Inspect the code below.

string debugStatement = "Error Generated at  for function";//Starting string//Starting string
string? timestamp = null;//Date that we want to insert but since it is null an exception will be thrown
int index = 19;//Start index of the insert which will cause an exception
string completedStatement = InsertText(index, debugStatement, timestamp);//Call the updated insert function
Console.WriteLine(completedStatement);//Display result
string InsertText(int index, string originalText, string textToInsert)
{
    if (index < 0 || index > originalText.Length - 1)
    {
        return originalText;
    }
    if(string.IsNullOrEmpty(textToInsert))//Add null check 
    {
        return originalText;
    }
    string newText = originalText.Insert(index, textToInsert);
    return newText;
}
Code Output
Error Generated at 5/1/2022 2:15:46 PM  for function
C# Programming for Unity Game Development Specialization

COURSERA

C# Programming for Unity Game Development Specialization

4.7 (2,230 reviews)

Beginner level

No previous experience is necessary

3-months at 10 hours a week (At your pace)

$59 / month or audit, and financial aid available

If you want to learn more about C# then check out this course on Coursera. It's a 3 month course to take you through the basics of C#.

You can get started with programming using C# and apply it to Unity games in this beginner-level program. Facilitated by the University of Colorado, the program offers a chance to grasp the basics of C# and utilize the knowledge to develop Unity games.

[Full Disclosure: As an affiliate, I receive compensation if you purchase through this link]

Start Your 7-day Free Trial

When Might This Function Be Used?

Fixed position or repeated patterns

Cases when it is known where the insert index will be all the time and also if there. For example, date and time when it is known that the day, month, or year are a fixed position and length. Also, look for repeated patterns where you might use the indexOf to find a certain character or set of characters to find the insert point.

Readability

Another consideration when using this function is how this might keep the code simple and readable so that whenever you can keep the code simple so that others can who might work on the code can come in a quickly understand what is going on that is a good thing. So having this function describes what is doing is useful for readability.

Alternate String Insert Methods

There are other ways of inserting a string into a string because often times when we just don't need to insert one string we need to insert multiple strings at a time. So below are some ways in which we can insert multiple strings into a string at one time.

String Replace

Placeholders for strings can be put in string then we use string replace insert at the place holder for that we want to replace. See the example below.

string GetQuery(int fileId, string fileType, int userId)
{
    string query = @"select 
                    * 
                    from 
                    file_main 
                    where 
                    file_id = [FILE_SCOPE] 
                    and file_type = [TYPE] 
                    and user_id = [USER]";
    query = query.Replace("[FILE_SCOPE]", fileId.ToString());//Replace [FILE_SCOPE] with fileId variable
    query = query.Replace("[TYPE]", fileType);//Replace [TYPE] with fileType variable
    query = query.Replace("[USER]", userId.ToString());//Replace [USER] with userId variable
    return query;
}
int fileId = 2318;
string fileType = "CSV";//CSV is a common file type
int userId = 3248;
string queryComplete = GetQuery(fileId, fileType, userId);
Console.WriteLine(queryComplete);
Code Output
select
    *
from
    file_main
where
    file_id = 2318
    and file_type = CSV
    and user_id = 3248
              
String Format

String format use places holders in curly braces starting with 0,1,..n to how many parameters you want to insert into the string. A simple example is below.

string GetQuery(string lastName, string userType)
{
    string query = @"select 
                    * 
                    from 
                    user_main 
                    where 
                    last_name = {0}
                    and user_type = {1}";
    string finalQuery = string.Format(query, lastName, userType);
    return finalQuery;
}
string lastName = "Shepard";
string userType = "ADMIN";
string queryComplete = GetQuery(lastName, userType);
Console.WriteLine(queryComplete);
Code Output
select
*
from
user_main
where
last_name = Shepard
and user_type = ADMIN
String Concatenation

This type of string insert can be used to combine different strings or insert variables into strings but it can be tedious to construct when as sections and variables increase.

string GetQuery(string lastName, string userType)
{
    string query = "select " +
                    " * " + 
                    " from" +
                    " user_main " +
                    " where " +
                    " last_name = " + lastName +
                    " and user_type = " + userType;
    string finalQuery = string.Format(query, lastName, userType);
    return finalQuery;
}
string lastName = "Shepard";
string userType = "ADMIN";
string queryComplete = GetQuery(lastName, userType);
Console.WriteLine(queryComplete);
Code Output
select  *  from user_main  where  last_name = Shepard and user_type = ADMIN 
String Interpolation

This way allows to place the variables in line similar to concatenation but it is easier because there is less formatting needed.

string GetQuery(int fileId, string fileType, int userId)
{
    string query = $"select * from file_main where file_id = {fileId} and file_type = {fileType} and user_id = {userId}";
    return query;
}
int fileId = 2318;
string fileType = "CSV";//CSV is a common file type
int userId = 3248;
string queryComplete = GetQuery(fileId, fileType, userId);
Console.WriteLine(queryComplete);
Code Output
select * from file_main where file_id = 2318 and file_type = CSV and user_id = 3248

How String Insert Works

There can be many ways to create a string insert function. One way is to use a substring to take the substring to the index and take the substring of the index to the end of the string. Then take the text we want to insert and concatenate it in between the two substrings. See the code snippet below.

string InsertInString(string originalText, int index, string textToInsert)
{
    if (index < 0 || index > originalText.Length - 1)//Add index check
    {
        return originalText;
    }
    if (string.IsNullOrEmpty(textToInsert))//Add null check 
    {
        return originalText;
    }
    string firstHalf = originalText.Substring(0, index);//Substring of the first half the text
    string secondHalf = originalText.Substring(index, (originalText.Length) - index); //Substring of the second half the text
    string final = firstHalf + textToInsert + secondHalf;//Concatenate all the strings together
    return final;
}
string debugStatement = "Error Generated at  for function";//Starting string
DateTime timestamp = DateTime.Now;//Date that we want to insert
int index = 19;//Start index of the insert which will cause an exception
string completedStatement = InsertInString(debugStatement, index, timestamp.ToString());//Call the insert function
Console.WriteLine(completedStatement);//Display result
Code Output
Error Generated at 5/8/2022 3:42:16 PM for function 

Conclusion

String Insert gives you a quick option to put text into another. Using the index, you can use it for automated processes or string generation. It has good readability as it describes exactly what it is doing. This is different from the alternative methods that can get the same result as an insert but don't convey that it is inserting. So insert is good for beginners and it's simple with only two parameters.

Get Latest Updates