This post will discuss how to check if a string consists of alphanumeric characters or not in C#.

There are several methods to determine whether the given string is alphanumeric (consists of only numbers and alphabets) in C#:

1. Using Regular Expression

The idea is to use the regular expression ^[a-zA-Z0-9]*$, which checks the string for alphanumeric characters. This can be done using the Regex.IsMatch() method, which tells whether this string matches the given regular expression. To restrict empty strings, use + instead of *.

Download  Run Code

 
If the regular expression is frequently called, you might want to compile the regular expression for the performance boost. This results in faster execution but increases startup time.

Download  Run Code

2. Using Enumerable.All() method

LINQ’s All() method returns true when all elements of a sequence satisfy a condition. To test for alphanumeric characters, pass the IsLetterOrDigit to the All() method.

Download  Run Code

 
Note that the IsLetterOrDigit() method does not strictly check for characters in ASCII range A-Z, a-z, and 0-9. We can use the following code to strictly check for ASCII alphabets and numbers:

Download  Run Code

3. Naive Solution

A naive solution is to iterate over characters in the string and check each character to be alphanumeric. This is demonstrated below:

Download  Run Code

That’s all about determining whether a string consists of alphanumeric characters in C#.