In C#, a literal is a notation used to represent a fixed value directly in the source code. Literals are used to provide values for variables, constants, or expressions without needing to compute or convert the values explicitly.
Essentially, literals are the actual values that you write in your code.
C# supports various types of literals for different data types, such as integers, floating-point numbers, characters, strings, booleans, and more.
Integer literals represent whole number values. They can be written in decimal, binary, or hexadecimal format.
int decimalLiteral = 42; // Decimal int binaryLiteral = 0b101010; // Binary int hexLiteral = 0x2A; // Hexadecimal
Floating-point literals represent real numbers with fractional parts. They can be of type float or double.
double doubleLiteral = 3.14159; float floatLiteral = 2.71828f; // Suffix 'f' indicates a float
Character literals represent single characters and are enclosed in single quotes.
char charLiteral = 'A'; char escapeChar = '\n'; // Newline character char unicodeChar = '\u03A9'; // Unicode character
String literals represent sequences of characters and are enclosed in double quotes.
string stringLiteral = "Hello, SmallCode!"; string escapeString = "This is a \"quoted\" string.";
Boolean literals represent true or false values.
bool trueLiteral = true; bool falseLiteral = false;
The null literal represents a reference that doesn't point to any object.
object nullLiteral = null;
Verbatim string literals ignore escape characters and are defined using the @ symbol.
string verbatimString = @"C:\User\Documents";
Interpolated strings allow you to embed expressions within a string using the $ symbol.
string name = "Vikas"; int age = 30; string interpolatedString = $"My name is {name} and I am {age} years old.";
DateTime literals represent specific dates and times.
DateTime dateLiteral = new DateTime(2023, 8, 15);
TimeSpan literals represent a duration of time.
TimeSpan timeSpanLiteral = TimeSpan.FromHours(2);
Type literals represent the Type object associated with a specific type.
Type typeLiteral = typeof(int);