In this blog post, we are going to learn how we can get the first character of a string in C#.

We will discuss 2 methods by which we can get the first character of a string. Just note that you should still check if the string is null or empty to avoid any runtime exceptions.

We will make use of the .Length property and the .Substring() method to get the first character in the string.

 

 

 

 

Get First Character Of A String In C# Using The Array Position 0

In this method, we will get the first character of the string using the array property and getting the first position by using the 0 index.

 

Example:

namespace ConsoleApp { public class Program { public static void Main() { string sampleString = "Code Like A Dev"; char firstCharacter = sampleString[0]; Console.WriteLine(firstCharacter); } } }

 

Result:

C

 

 

Get First Character Of A String Using the .Substring() Method In C#

In this method, we will use the .Substring method on a string to calculate the first character. So we will tell the substring method to start the index at 0 and then take 1 character to get the first character.

 

Example:

namespace ConsoleApp { public class Program { public static void Main() { string sampleString = "Code Like A Dev"; string firstCharacter = sampleString.Substring(0, 1); Console.WriteLine(firstCharacter); } } }

 

Result:

C