Data Types in C#
Explore value types (int, double, bool, char, struct), reference types (string, object, class), nullable types, and the difference between stack and heap.
Value Types (Primitives)
1. Integer Types (byte, short, int, long)
C# has four signed integer types of increasing size. Use `int` for most cases.
2. Floating-Point Types (float, double, decimal)
C# has three floating-point types. Use `double` for general math, `decimal` for money.
3. bool and char
`bool` stores `true` or `false`. `char` stores a single Unicode character (16-bit).
Reference Types
1. string
`string` is a reference type but behaves like a value type — it is immutable. Two strings with the same content are equal.
2. object (Base Type)
`object` is the root type of all C# types. Any value — value type or reference type — can be assigned to an `object` variable.
3. dynamic (Runtime Typing)
`dynamic` bypasses compile-time type checking — the type is resolved at runtime. Similar to JavaScript's dynamic nature.
4. object vs dynamic — Key Difference
`object` is type-checked at compile time (you must cast before using). `dynamic` skips compile-time checks entirely — errors only surface at runtime.
Stack vs Heap Memory
1. Value Types vs Reference Types in Memory
Value types live on the stack — fast and automatically cleaned up. Reference types live on the heap — managed by the garbage collector.
Type Casting
1. Implicit Casting (Widening)
Implicit casting happens automatically when converting to a larger type — no data is lost.
2. Explicit Casting (Narrowing)
Explicit casting is required when converting to a smaller type — data may be lost.
3. Convert and Parse
Use `Convert.ToX()` or `int.Parse()` / `int.TryParse()` to convert strings and between types safely.
Nullable Types
1. Nullable Value Types (int?, bool?)
By default, value types cannot be `null`. Adding `?` makes them nullable — useful for optional data like database fields.
2. Null-Coalescing Operators (?? and ??=)
`??` returns a fallback if the value is null. `??=` assigns the fallback only if the variable is currently null.
Printing the Data Type
1. Using GetType()
`GetType()` returns the exact runtime `Type` object. Use `GetType().Name` for a short readable name.
2. Type Check using is
The `is` keyword checks if a variable is of a given type — and can declare a typed variable in one step (pattern matching).