Data Types in C#
C# is a strongly typed language with value types and reference types.
Value Types (stored on stack):
- Numeric: int, long, float, double, decimal
- Boolean: bool
- Character: char
- Struct and enum
Reference Types (stored on heap):
- string
- object
- class instances
- arrays
var Keyword: Type inference - compiler figures out the type.
Nullable Types: Value types can be made nullable with ?. C# 8+ has nullable reference types.
const vs readonly:
- const: Compile-time constant
- readonly: Runtime constant (can be set in constructor)
Code Examples
C# Data Typescsharp
// Value types
int number = 42;
long bigNumber = 9999999999L;
float singlePrecision = 3.14f;
double doublePrecision = 3.14159265359;
decimal money = 19.99m; // For financial calculations
bool isActive = true;
char letter = 'A';
Console.WriteLine($"int: {number}");
Console.WriteLine($"decimal: {money}");
// Type inference with var
var inferredString = "Hello"; // string
var inferredInt = 42; // int
var inferredList = new List<string>(); // List<string>
// Nullable value types
int? nullableInt = null;
nullableInt = 42;
if (nullableInt.HasValue)
{
Console.WriteLine($"Value: {nullableInt.Value}");
}
// Null coalescing
int result = nullableInt ?? 0; // Use 0 if null
// String types
string greeting = "Hello";
string multiLine = """
This is a
multi-line string
""";
// Constants
const double PI = 3.14159;
// PI = 3.14; // Error! Cannot modify const
// Implicit vs explicit casting
int intVal = 100;
double doubleVal = intVal; // Implicit (safe)
int backToInt = (int)doubleVal; // Explicit (may lose data)
Console.WriteLine($"Converted: {backToInt}");C# has distinct value and reference types. Use decimal for financial calculations to avoid floating-point errors.
Quick Quiz
1. Which type should you use for financial calculations in C#?
Was this lesson helpful?