c# - How to append a char to a string

Append a Char to a String
The String represents text as a sequence of UTF-16 code units. The String is a sequential collection of characters that is used to represent text. The String is a sequential collection of System.Char objects.

The following .net c# tutorial code demonstrates how we can append a Char to a String. In this .net c# tutorial code we will append a Char object to a String object. Here we will append a Char ‘L’ to the String using the String Insert() method and we also add a Char to the String instance using a plus operator.

The Char represents a character as a UTF-16 code unit. We can simply append a Char instance to a String object by a plus operator. The plus operator adds the specified Char object at the end of the specified String instance. The result also returns a String object.

The String Insert() method returns a new String in which a specified String is inserted at a specified index position in the instance. So using the String Insert(int startIndex, string value) method we can append a Char object to the String instance.

We have to convert the Char object to a String object and we also pass the length of the String for the startIndex parameter. So, the method returns a String instance where the specified Char object is appended to the source String. The Insert() method throws ArgumentNullException if the value is null. It also throws ArgumentOutOfRangeException if the startIndex is negative or greater than the length of this instance.

<%@ Page Language="C#" AutoEventWireup="true"%>

<!DOCTYPE html>  
<script runat="server"> 
    protected void Button1_Click(object sender, System.EventArgs e)  
        //this section create a string variable.
        string stringOfChars = "ABCDEFGHIJK";
        Label1.Text = "string of chars..................<br />";
        Label1.Text += stringOfChars;

        //this line create a char variable with value 'L'
        Char c = 'L';

        //this line append character 'L' on string (insert at string last)
        stringOfChars = stringOfChars.Insert(stringOfChars.Length,c.ToString());

        //another way to append character on string
        //stringOfChars += c;

        Label1.Text += "<br /><br />string after append char 'L'...........<br />";
        Label1.Text += stringOfChars;
<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>c# example - string append char</title>  
    <form id="form1" runat="server">  
        <h2 style="color:MidnightBlue; font-style:italic;">  
            c# example - string append char
        <hr width="550" align="left" color="Gainsboro" />  
        <br /><br />
            Text="string append char"  
More c# examples