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
What are integer literals in C#?
An integer literal in C# is a constant numeric value written directly in the code. Integer literals can be decimal (base 10) or hexadecimal (base 16) constants. A prefix specifies the base: 0x or 0X for hexadecimal, with no prefix for decimal. They can also have suffixes like U for unsigned and L for long.
Syntax
Following is the syntax for different types of integer literals −
// Decimal literals 123 200L // long 456U // unsigned int 789UL // unsigned long // Hexadecimal literals 0xFF // 255 in decimal 0x1A // 26 in decimal 0X2BL // long hexadecimal
Types of Integer Literals
| Type | Suffix | Example | Description |
|---|---|---|---|
| int | None | 200 | 32-bit signed integer |
| unsigned int | U or u | 90u | 32-bit unsigned integer |
| long | L or l | 300L | 64-bit signed integer |
| unsigned long | UL or ul | 400UL | 64-bit unsigned integer |
Using Decimal Integer Literals
Decimal literals are the most common type, written without any prefix −
using System;
class Program {
static void Main(string[] args) {
// Different decimal integer literals
int a = 200;
uint b = 90u;
long c = 300L;
ulong d = 400UL;
Console.WriteLine("int: " + a);
Console.WriteLine("unsigned int: " + b);
Console.WriteLine("long: " + c);
Console.WriteLine("unsigned long: " + d);
}
}
The output of the above code is −
int: 200 unsigned int: 90 long: 300 unsigned long: 400
Using Hexadecimal Integer Literals
Hexadecimal literals start with 0x or 0X prefix and use digits 0-9 and letters A-F −
using System;
class Program {
static void Main(string[] args) {
// Hexadecimal integer literals
int hex1 = 0xFF; // 255 in decimal
int hex2 = 0x1A; // 26 in decimal
long hex3 = 0x2BL; // 43 in decimal
uint hex4 = 0xABCDu; // 43981 in decimal
Console.WriteLine("0xFF = " + hex1);
Console.WriteLine("0x1A = " + hex2);
Console.WriteLine("0x2BL = " + hex3);
Console.WriteLine("0xABCDu = " + hex4);
}
}
The output of the above code is −
0xFF = 255 0x1A = 26 0x2BL = 43 0xABCDu = 43981
Binary Literals (C# 7.0+)
Starting with C# 7.0, you can also use binary literals with the 0b prefix −
using System;
class Program {
static void Main(string[] args) {
// Binary integer literals (C# 7.0+)
int binary1 = 0b1010; // 10 in decimal
int binary2 = 0b11110000; // 240 in decimal
Console.WriteLine("0b1010 = " + binary1);
Console.WriteLine("0b11110000 = " + binary2);
}
}
The output of the above code is −
0b1010 = 10 0b11110000 = 240
Conclusion
Integer literals in C# provide a flexible way to represent constant numeric values in decimal, hexadecimal, or binary formats. They support various suffixes to specify the exact integer type needed, making them essential for precise numeric programming and memory-efficient code.
