Value types - Store their data directly. A variable of a value type contains the value itself. - Examples: int, double, decimal, bool, char, DateTime, enums, and structs (including records declared as record struct). - Assignment copies the value: changing the copy does not affect the original. int a = 10; int b = a; // copy b = 20; // a is still 10 - Stored inline: as locals (typically on the stack) or inside the object or array that contains them. - Cannot be null unless declared nullable (int?). Reference types - A variable holds a reference (pointer) to an object on the managed heap. - Examples: class, interface, delegate, arrays, string, object, record (class). - Assignment copies the reference, so both variables point to the same object. var c1 = new Customer { Name = "Asha" }; var c2 = c1; // same object c2.Name = "Ravi"; // c1.Name is also "Ravi" - Can be null; memory is managed by the garbage collector. Note: "value types live on the stack" is a simplification. A value type field inside a class lives on the heap with that object; what matters is copy semantics. What about string? string is a reference type (System.String is a class), but it behaves like a value type in several ways: - Immutable: every "modification" (concatenation, Replace, ToUpper) creates a new string; the original never changes. - Value equality: == and Equals compare contents, not references (operator == is overloaded). string s1 = "hello"; string s2 = s1; s2 += " world"; // creates a new string; s1 is still "hello" Console.WriteLine(s1 == "hello"); // true — content comparison - String interning: identical string literals share one instance in memory. - Because of immutability, building strings in loops creates many objects; use StringBuilder (or string.Join, interpolation handlers) for heavy concatenation. Passing to methods - By default, value types pass a copy and reference types pass a copy of the reference (the method can modify the object but cannot replace the caller's variable). Use ref, out or in to pass by reference. Boxing - Converting a value type to object or an interface allocates a box on the heap; unboxing copies it back. Avoid it in hot paths by using generics.
Ravindra Wadile · · 0 likes