C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
There are many ways to see if a character is a whitespace character in the C# language. The char.IsWhiteSpace method is a useful option. It has some advanced behavior.
Example. In this first example, we see how the char.IsWhiteSpace method is called. Because it is a static method, you must specify the type in the composite name, not a variable. We use it three times.
It returns a boolean value, which means it can be used in the context of an if-expression. The lowercase letter 'a' is not a whitespace char. The space and the \n are whitespace chars.
C# program that uses char.IsWhiteSpace method using System; class Program { static void Main() { // Tests the char.IsWhiteSpace method three times. char value = 'a'; if (char.IsWhiteSpace(value)) { Console.WriteLine(1); } value = ' '; if (char.IsWhiteSpace(value)) { Console.WriteLine(2); } value = '\n'; if (char.IsWhiteSpace(value)) { Console.WriteLine(3); } } } Output 2 3
Implementation. How is the char.IsWhiteSpace method internally implemented in the .NET Framework? You will see that the IsWhiteSpace method first calls an IsLatin1 method. In most cases this method will return true.
Then: The IsWhiteSpaceLatin1 method is called and its return value is propagated.
Obviously: If you can make assumptions about your characters, you can simply use the logical tests inside the IsWhiteSpaceLatin1 method.
Implementation of char.IsWhiteSpace: C# public static bool IsWhiteSpace(char c) { if (IsLatin1(c)) { return IsWhiteSpaceLatin1(c); } return CharUnicodeInfo.IsWhiteSpace(c); } private static bool IsLatin1(char ch) { return (ch <= '\x00ff'); } private static bool IsWhiteSpaceLatin1(char c) { if (((c != ' ') && ((c < '\t') || (c > '\r'))) && ((c != '\x00a0') && (c != '\x0085'))) { return false; } return true; }
Summary. The meaning of the char.IsWhiteSpace method is clear enough. But its implementation and actual behavior is worth noticing and exploring further. We saw that the IsWhiteSpace method has advanced support for Unicode characters.