While there are many ways to skin this cat, I prefer to wrap such code into reusable extension methods that make it trivial to do going forward. When using extension methods, you can also avoid RegEx as it is slower than a direct character check. I like using the extensions in the Extensions.cs NuGet package. It makes this check as simple as:
using Extensions;
" to the top of your code."smith23".IsAlphaNumeric()
will return True whereas "smith 23".IsAlphaNumeric(false)
will return False. By default the .IsAlphaNumeric()
method ignores spaces, but it can also be overridden as shown above. If you want to allow spaces such that "smith 23".IsAlphaNumeric()
will return True, simple default the arg.MyString.IsAlphaNumeric()
.