C# Char Struct

Char Struct

In C#, the char struct is used to represent a single Unicode character. It's a value type and is an alias for the System.Char structure. The char type occupies 2 bytes in memory, which allows it to represent any Unicode character in the UTF-16 encoding.

Here's a tutorial on the char struct:

1. Declaring and Initializing:

You can declare and initialize a char variable like this:

char ch1 = 'A'; char ch2 = '\u0041'; // Using Unicode code point 

2. Escape Sequences:

There are special characters that can't be directly represented in a string or character literal. For these, we use escape sequences:

char newline = '\n'; // New line char tab = '\t'; // Tab char backslash = '\\'; // Backslash itself char quote = '\''; // Single quote char doubleQuote = '\"'; // Double quote 

3. Properties and Methods:

The char struct provides several useful methods and properties:

  • IsDigit(): Checks if the character is a digit.

    bool isDigit = char.IsDigit('5'); // true 
  • IsLetter(): Checks if the character is a letter.

    bool isLetter = char.IsLetter('a'); // true 
  • IsWhiteSpace(): Checks if the character is a whitespace character.

    bool isSpace = char.IsWhiteSpace(' '); // true 
  • ToLower(): Converts the character to lowercase.

    char lower = char.ToLower('A'); // 'a' 
  • ToUpper(): Converts the character to uppercase.

    char upper = char.ToUpper('a'); // 'A' 

4. Converting to Other Types:

You can convert a char to its numeric Unicode code point using an explicit cast:

char ch = 'A'; int unicodeValue = (int)ch; // 65 

You can also convert a number back to its Unicode representation:

int value = 65; char chFromInt = (char)value; // 'A' 

5. Comparison:

Characters can be compared using the standard comparison and equality operators:

char a = 'A'; char b = 'B'; bool areEqual = a == b; // false bool isALessThanB = a < b; // true 

Example: Checking Type of Character:

Here's a simple program that uses the char struct to check and display the type of character entered:

using System; namespace CharExample { class Program { static void Main() { Console.WriteLine("Enter a single character:"); char ch = Console.ReadKey().KeyChar; Console.WriteLine("\nYou entered: " + ch); if (char.IsDigit(ch)) { Console.WriteLine("It's a digit."); } else if (char.IsLetter(ch)) { Console.WriteLine("It's a letter."); } else if (char.IsWhiteSpace(ch)) { Console.WriteLine("It's a whitespace."); } else { Console.WriteLine("It's a different type of character."); } } } } 

This tutorial provides an introduction to the char struct in C#. The char type is fundamental in C# and understanding its properties and methods can be beneficial when dealing with text processing tasks.


More Tags

web-frontend postgresql-11 product-variations mapi perspectivecamera pyodbc reactstrap dice resteasy system.drawing

More Programming Guides

Other Guides

More Programming Examples