c# - How to get the first character of a string

String get first character
The following asp.net c# example code demonstrate us how can we get the first character of a string programmatically at run time in an asp.net application. .Net framework's String Class represent text as a series of Unicode characters. String Class has no direct method or property to get its first character. So, we need to convert the string object value to a char array.

String.ToCharArray() method copies the characters in this instance to a Unicode character array. .Net framework's Enumerable.ElementAt<TSource>() method return the element at a specified index in a sequence. So, we can get char array first element by calling the ElementAt() method as this way CharArray.ElementAt(0). .Net framework's Array object contain zero (0) based index. Here, char array first element represent the first character of string.

<%@ 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 plants = "Brown Betty. Meadow Cabbage. Catalina Ironwood. Wild Black Cherry.";

        Label1.Text = "string of plants..................<br />";
        Label1.Text += plants+"<br />";

        //this line get first character of string.
        char ch = plants.ToCharArray().ElementAt(0);

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