Literals in C# with Explanation
In C#, literals are the literal or constant values
that are directly written in your code without any variables or calculations.
Here's an explanation of different types of literals in C#:
1.
Integer Literals:
v Integer
literals are used to represent whole numbers without decimal points.
v They
can be specified in decimal (base 10), hexadecimal (base 16), octal (base 8),
or binary (base 2) formats.
v Examples:
int decimalValue = 42; //
Decimal literal
int hexadecimalValue = 0x2A; //
Hexadecimal literal
int octalValue = 052; //
Octal literal
int binaryValue = 0b101010; //
Binary literal
2.
Floating-Point Literals:
v Floating-point
literals are used to represent real numbers with a fractional part.
v They
can be specified using decimal notation or scientific notation.
v Examples:
double decimalValue = 3.14;
// Decimal notation
double scientificValue = 1.23e4; // Scientific notation (1.23 x 10^4)
3.
Character Literals:
v Character
literals represent single characters enclosed in single quotes.
v They
can include special escape sequences such as newline (`\n`), tab (`\t`),
backspace (`\b`), etc.
v Examples:
char ch = 'A';
char newLine = '\n';
4.
String Literals:
v String
literals represent a sequence of characters enclosed in double quotes.
v They
can include escape sequences for special characters and formatting.
v Examples:
string message = "Hello, World!";
string filePath = "C:\\temp\\file.txt"; // Backslash escape sequence
5.
Boolean Literals:
v Boolean
literals represent the logical values `true` or `false`.
v Examples:
bool isTrue = true;
bool isFalse = false;
6.
Null Literal:
v The
null literal represents a null reference.
v It
is often used to indicate the absence of an object.
v Example:
string name = null;
7.
Verbatim String Literals:
v Verbatim
string literals are prefixed with `@` and allow you to include special
characters and escape sequences without interpretation.
v They
are often used for file paths, regular expressions, or any other string that
requires a lot of backslashes or special characters.
v Example:
string filePath = @"C:\temp\file.txt";
Literals provide fixed values that are used directly
in your code. They are useful for initializing variables, specifying constant
values, or representing specific data in your programs. By understanding and
utilizing literals, you can effectively represent different types of data in
your C# code.
0 Comments