What is the difference between a reference type and value type in c#?

后端 未结 14 2412
谎友^
谎友^ 2020-11-21 05:13

Some guy asked me this question couple of months ago and I couldn\'t explain it in detail. What is the difference between a reference type and a value type in C#?

I

14条回答
  •  旧巷少年郎
    2020-11-21 05:53

    I found it easier to understand the difference of the two if you know how computer allocate stuffs in memory and know what a pointer is.

    Reference is usually associated with a pointer. Meaning the memory address where your variable reside is actually holding another memory address of the actual object in a different memory location.

    The example I am about to give is grossly over simplified, so take it with a grain of salt.

    Imagine computer memory is a bunch of PO boxes in a row (starting w/ PO Box 0001 to PO Box n) that can hold something inside it. If PO boxes doesn't do it for you, try a hashtable or dictionary or an array or something similar.

    Thus, when you do something like:

    var a = "Hello";

    the computer will do the following:

    1. allocate memory (say starting at memory location 1000 for 5 bytes) and put H (at 1000), e (at 1001), l (at 1002), l (at 1003) and o (at 1004).
    2. allocate somewhere in memory (say at location 0500) and assigned it as the variable a.
      So it's kind of like an alias (0500 is a).
    3. assign the value at that memory location (0500) to 1000 (which is where the string Hello start in memory). Thus the variable a is holding a reference to the actual starting memory location of the "Hello" string.

    Value type will hold the actual thing in its memory location.

    Thus, when you do something like:

    var a = 1;

    the computer will do the following:

    1. allocate a memory location say at 0500 and assign it to variable a (the same alias thing)
    2. put the value 1 in it (at memory location 0500).
      Notice that we are not allocating extra memory to hold the actual value (1). Thus a is actually holding the actual value and that's why it's called value type.

提交回复
热议问题