This article illustrates the different techniques to check if a string contains only letters in C#.

1. Using String.All() method

To determine if a string contains only letters in C#, you can use Enumerable.All() method by LINQ. It returns true if all elements of a sequence satisfy a condition, false otherwise. To check for only letters, pass Char.IsLetter to the All() method.

Download  Run Code

 
It should be noted that the Char.IsLetter method determines whether the char is a Unicode letter. To restrict checking for only ASCII alphabets, do like:

Download  Run Code

 
To check for Unicode letters with only space allowed, you can do like:

Download  Run Code

 
Finally, if you need to check for either Unicode letters or digits, pass the Char.IsLetterOrDigit to the All() method. To check for only numbers, you can use the Char.IsDigit method.

Download  Run Code

2. Using Regex.IsMatch() method

You can also use regular expressions to identify any non-alpha characters in a string. To check only for ASCII letters, you can use regex ^[a-zA-Z]+$. To check for only ASCII letters and numbers, you can use regex ^[a-zA-Z0-9]+$. Similarly, to check for ASCII letters, numbers, and underscore, use regex ^[a-zA-Z0-9_]+$.

Download  Run Code

 
To check only for Unicode letters, you can use the pattern ^[\p{L}]+$. To check for only Unicode letters and numbers, you can use the pattern ^[\p{L}\p{N}]+$. Similarly, to check for Unicode letters, numbers, and underscore, use the pattern ^[\w]+$.

Download  Run Code

3. Using foreach

If you are not allowed to use LINQ or Regex, try using the below code. It uses a basic foreach loop to traverse the string and determine if each character is a letter or not. The following code checks for Unicode letters, but it can be easily modified to check for ASCII letters.

Download  Run Code

That’s all about checking if a string contains only letters in C#.