Determine the value of a char in CSharp

To determine the value of a char, we can use the built-in static methods on the System.Char structure.
The following methods can be used:

  • Char.IsControl
  • Char.IsDigit
  • Char.IsLetter
  • Char.IsNumber
  • Char.IsPunctuation
  • Char.IsSeparator
  • Char.IsSurrogate
  • Char.IsSymbol
  • Char.IsWhitespace

To return the kind of a character. First, create an enumeration to define the various types of characters:

public enum CharKind
{
Digit,
Letter,
Number,
Punctuation,
Unknown
}

Next, create the extension method that contains the logic to determine the kind of a character and to return a CharKind enumeration value indicating that type:

static class CharStrExtMethods
{
public static CharKind GetCharKind(this char theChar)
{
if (Char.IsLetter(theChar))
{
return CharKind.Letter;
}
else if (Char.IsNumber(theChar))
{
return CharKind.Number;
}
else if (Char.IsPunctuation(theChar))
{
return CharKind.Punctuation;
}
else
{
return CharKind.Unknown;
}
}
}

Example:

string data = "abcdefg";
if (GetCharKind(data[4]) == CharKind.Digit) {...}

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.