DEV Community

Discussion on: Explain reference and value types like I'm five

Collapse
 
nestedsoftware profile image
Nested Software • Edited

I’ll take a stab at this...

  • You want to read a book. In your room there’s a box. You look inside the box and there is a book. You start to read the book. In this case we can think of the box as a “value type.” It directly contains the thing you’re interested in.

  • This time the box just has a card in it. The card tells you where to find a given book on the bookshelf. In this case the box is a “reference type.” It tells you where the thing you want can be found but it’s not something that you need on its own.

You can think of any variable as a box, i.e. a location in memory. If that location contains an actual value of interest, then in this sense it can be considered a value type. If it points to another location in memory, then it’s a reference type. In this sense, things that take more than one memory location, like strings or arrays, are generally reference types by default.

However, I think that value type semantics can be applied to any type. It would mean, for example, that something like a = b = SOMETHING would create a copy for a and changing that value would not affect b.