C# Data Types
A data type tells C# what kind of value a variable can hold and how much memory to set aside for it. Because C# is strongly typed, choosing the right data type is essential and helps the compiler catch mistakes before your program ever runs.
Two Families of Types
C# data types fall into two broad groups. Value types hold their data directly, such as numbers and true/false values. Reference types hold a reference to where the data is stored in memory, such as strings and arrays. As a beginner you will mostly work with the built-in value types plus string.
Numeric Types
Numbers come in whole-number and decimal varieties. Use int for typical whole numbers, long for very large whole numbers, double for general decimals, and decimal when you need high precision, such as money. Each type reserves a different amount of memory and can hold a different range of values.
Declaring numeric types
int itemCount = 12;
long population = 1400000000L;
double temperature = 36.6;
decimal price = 19.99m;
Console.WriteLine(itemCount);
Console.WriteLine(price);Text: char and string
A char holds exactly one character and is written with single quotes. A string holds any number of characters and is written with double quotes. These two are easy to mix up, so remember: single quotes for one character, double quotes for text.
Characters and strings
char grade = 'A';
string name = "Priya";
Console.WriteLine(grade); // Outputs: A
Console.WriteLine(name); // Outputs: PriyaBooleans
The bool type can only hold one of two values: true or false. Booleans are the backbone of decision-making in your programs, because they power if statements, loops, and comparisons.
- int is your default choice for whole numbers.
- double is the default for decimal numbers.
- decimal is preferred for money to avoid rounding errors.
- string stores text; char stores a single character.
- bool stores true or false and drives program logic.
Exercise: C# Data Types
What is the default value of an uninitialized int field?