Data Types
C# has two top-level type families: value types (numbers, structs, enums — stored inline) and reference types (classes, strings, arrays, delegates — stored on the heap, accessed via a reference).
Value types vs reference types
EXAMPLE
// Value types — small, copied on assignment
int age = 36;
double pi = 3.14159;
decimal money = 99.95m; // exact decimal
bool ok = true;
char c = 'A';
struct Point { public int X, Y; }
// Reference types — accessed through references
string s = "Ada";
int[] nums = { 1, 2, 3 };
List<int> list = new();
class User { public string Name { get; set; } }
// Records — reference types with value equality + with-syntax
public record Person(string Name, int Age);
var p1 = new Person("Ada", 36);
var p2 = p1 with { Age = 37 }; // immutable copy
Console.WriteLine(p1 == new Person("Ada", 36)); // True (value equality)
// Nullable reference types — enable in csproj
string? maybe = null;
int len = maybe?.Length ?? 0;
Why it matters
Use decimal (not double) for money. Use record for immutable data carriers. Turn nullable reference types ON in every new project.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Example
Example
byte b = 1; int i = 10; long l = 99L; float f = 1.5f; double d = 2.5; decimal m = 9.99m; bool t = true; char c = 'A';Try it Yourself »
Discussion
Loading…