-1

I know what both are, value and reference, but my question is why do both exist?

I mean why all primitives aren't also reference (or treated as such)? I know the primitives aren't affected by garbage collector, which i see as a drawback, and I can't find any pros to them, so what am I missing?

relysis
  • 1,065
  • 1
  • 14
  • 27
  • 1
    One reason is efficiency. Having to allocate a reference for every integer, character, and boolean would use up an unnecessary amount of memory. – Joe Sewell Jan 21 '19 at 21:00
  • 1
    A useful read here is "[The Stack Is An Implementation Detail, Part One](https://blogs.msdn.microsoft.com/ericlippert/2009/04/27/the-stack-is-an-implementation-detail-part-one/)" by Eric Lippert. – Wai Ha Lee Jan 21 '19 at 21:00
  • Possible duplicate of [Passing Objects By Reference or Value in C#](https://stackoverflow.com/questions/8708632/passing-objects-by-reference-or-value-in-c-sharp) – arghtype Jan 21 '19 at 21:24

3 Answers3

2

I mean why all primitives aren't also reference (or treated as such)? I know the primitives aren't affected by garbage collector, which i see as a drawback

Consider the following very common code:

 for (var i = 0; i < 1000; i++)
     for (var j = 0; j < 1000; j++)

Now imagine thats called once every second… that would be 1 000 000 reference types created every second that have to be allocated in the heap, kept track of, and collected by the GC. And you would see this as an advantage? Think again...

InBetween
  • 32,319
  • 3
  • 50
  • 90
0

Two reasons I can come up with quickly:

  1. Because a reference can be changed by the called function, so it can have side effects.
  2. Also, for partly historic reasons, passing a char/byte or 2 byte only takes 1 or 2 bytes, while a reference is normally 4 bytes.
Michel Keijzers
  • 15,025
  • 28
  • 93
  • 119
0

I know the primitives aren't affected by garbage collector, which i see as a drawback,

Why? You prefer more overhead and lower performance? I used properly, value types and NOT relying on the garbage collector are a very significant performance advantage.

TomTom
  • 61,059
  • 10
  • 88
  • 148