Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to define character constants in C#?
Character constants in C# are single characters enclosed in single quotes. They can be stored in variables of type char and represent individual characters, escape sequences, or Unicode characters.
Syntax
Following is the syntax for defining character constants −
char variableName = 'character';
Character constants can be −
Plain characters:
'a','X','5'Escape sequences:
',
''\t','''Unicode characters:
'\u0041'(represents 'A')
Common Character Constants
Here are the most commonly used character escape sequences −
| Escape Sequence | Character | Description |
|---|---|---|
| Newline | Moves cursor to next line | |
| \t | Tab | Horizontal tab character |
| \ | Backslash | Literal backslash |
| ' | Single quote | Literal single quote |
| " | Double quote | Literal double quote |
Using Character Constants
Example
using System;
class Program {
static void Main(string[] args) {
char letter = 'A';
char digit = '5';
char newline = '
';
char tab = '\t';
Console.WriteLine("Character constants:");
Console.WriteLine("Letter: " + letter);
Console.WriteLine("Digit: " + digit);
Console.WriteLine("Welcome!" + tab + newline + newline);
Console.WriteLine("This is it!");
}
}
The output of the above code is −
Character constants: Letter: A Digit: 5 Welcome! This is it!
Using Unicode Character Constants
Example
using System;
class Program {
static void Main(string[] args) {
char heart = '\u2665';
char smiley = '\u263A';
char copyright = '\u00A9';
char alpha = '\u03B1';
Console.WriteLine("Unicode characters:");
Console.WriteLine("Heart: " + heart);
Console.WriteLine("Smiley: " + smiley);
Console.WriteLine("Copyright: " + copyright);
Console.WriteLine("Alpha: " + alpha);
}
}
The output of the above code is −
Unicode characters: Heart: ? Smiley: ? Copyright: © Alpha: ?
Character Operations
Example
using System;
class Program {
static void Main(string[] args) {
char ch = 'A';
Console.WriteLine("Character: " + ch);
Console.WriteLine("ASCII value: " + (int)ch);
Console.WriteLine("Next character: " + (char)(ch + 1));
Console.WriteLine("Is digit? " + char.IsDigit(ch));
Console.WriteLine("Is letter? " + char.IsLetter(ch));
Console.WriteLine("To lowercase: " + char.ToLower(ch));
}
}
The output of the above code is −
Character: A ASCII value: 65 Next character: B Is digit? False Is letter? True To lowercase: a
Conclusion
Character constants in C# are defined using single quotes and can represent plain characters, escape sequences, or Unicode values. They are stored in char variables and provide methods for character manipulation and validation through the char class.
