Literals and Constants in C#

Literal is a source code representation of a value, i.e. it is a value that has been hard-coded directly into your source.

Example
x = 100;

x is a variable, and 100 is a literal.

Type of literals in C# are:

  1. Boolean Literal
  2. Integer Literal
  3. Real Literal
  4. Character Literal
  5. String Literal
  6. Null Literal

Boolean Literal

There are two Boolean literal values: true and false.

Example
bool open = true;

Integer Literal

Integer literals are used to write values of types int, uint, long, and ulong. Integer literals have two possible forms: decimal and hexadecimal.

Example
100 //decimal 0x123f //hexadecimal 072 //octal 1000 //integer 100u //uint 1000 //long 10ul //ulong

Real Literal

Real literals are used to write values of types float, double, and decimal.

Example
10.15 //double 100.72f //float 1.45d //double 1.44m //decimal e23 //exponent. Means 1023

Character Literal

A character literal represents a single character, and usually consists of a character in quotes, as in 'a'.

Example
C# Character Literal

String Literal

C# provides support for two types of string literals: regular string literals and verbatim string literals.

Regular string literals are enclosed within double quotes, such as "string". They can contain any sequence of characters, including escape sequences like "\t" for the tab character or "\n" for a new line. Additionally, regular string literals can also include hexadecimal or Unicode escape sequences to represent specific characters.

On the other hand, verbatim string literals are denoted by an "@" character preceding the opening double-quote, such as @"string". They allow for the inclusion of escape sequences and characters without the need for special handling. This means that backslashes "" within verbatim string literals are treated as ordinary characters, and no additional escaping is required. Verbatim string literals are particularly useful when working with file paths, regular expressions, or any scenario where backslashes or escape sequences are common.

Example
string a = "string, literal"; // string, literal string b = @"string, literal"; // string, literal string c = "string \t literal"; // string literal string d = @"string \t literal"; // string \t literal

Null Literal

Null Literal is literal that denotes null type. Moreover, null can fit to any reference-type . and hence is a very good example for polymorphism.

Example
int x = null; if (x == null) Console.WriteLine("This is null");

Constants

Constants are values which are fixed and cannot be changed anytime during program execution. They can be of any data type.

const float fl= 2.511;