C# char.IsWhiteSpace (If Char Is Space or Newline)

This C# example program uses the char.IsWhiteSpace method. It tests for spaces and newlines.
Char.IsWhiteSpace. The char.IsWhiteSpace method tests for spaces and newlines. 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.Char
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 3 times.Static

Return: IsWhiteSpace returns a boolean value, which means it can be used in the context of an if-expression.


Note: 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.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to
Dot Net Perls