As we learned in the Variables chapter, a variable in C# must be defined with a specific data type. The data type tells the compiler what size the memory space needs to be and what kind of values can be stored in it.
Choosing the correct data type is crucial for memory efficiency and performance.
Data types in C# are primarily divided into two main categories: Value Types and Reference Types.
Value types store the data directly in their own memory allocation. Examples include numbers, characters, and booleans.
| Data Type | Size | Description |
|---|---|---|
| int | 4 bytes | Stores whole numbers from -2,147,483,648 to 2,147,483,647. |
| long | 8 bytes | Stores very large whole numbers. End the value with L. |
| float | 4 bytes | Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits. End the value with F. |
| double | 8 bytes | Stores fractional numbers. Sufficient for storing 15 decimal digits. |
| bool | 1 bit | Stores true or false values. |
| char | 2 bytes | Stores a single character/letter, surrounded by single quotes. |
Reference types do not store the actual data directly. Instead, they store a reference (or memory address) to where the data is located. The most common reference type is a string.
When dealing with decimal numbers, double is the default type in C#. If you want to use a float, you must append an F or f to the end of the number.
using System;class Program { static void Main() { float myFloatNum = 5.75F; double myDoubleNum = 19.99; Console.WriteLine(myFloatNum); Console.WriteLine(myDoubleNum); } }
Pro Tip: There is also a `decimal` data type which takes 16 bytes. It has higher precision and smaller range, making it perfect for financial and monetary calculations. Append an `M` to use it (e.g., `decimal money = 19.99M;`).
var Keyword)Instead of explicitly stating the data type, you can use the var keyword. The C# compiler will automatically figure out the data type based on the value assigned to it.
var myName = "Alice"; // Compiler knows this is a string var myAge = 25; // Compiler knows this is an int
Note: You must assign a value immediately when using var, otherwise the compiler will throw an error because it cannot guess the type.
If you have a variable whose value should never change (like Pi or a database configuration URL), use the const keyword. This makes the variable "constant" and unchangeable.
const double PI = 3.14159; // PI = 3.14; // ERROR: This will cause a compiler error!
Which character must you append to a number to make it a float?