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

后端 未结 14 2482
谎友^
谎友^ 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:54

    Value type:

    Holds some value not memory addresses

    Example:

    Struct

    Storage:

    TL;DR: A variable's value is stored wherever it is decleared. Local variables live on the stack for example, but when declared inside a class as a member it lives on the heap tightly coupled with the class it is declared in.
    Longer: Thus value types are stored wherever they are declared. E.g.: an int's value inside a function as a local variable would be stored on the stack, whilst an in int's value declared as member in a class would be stored on the heap with the class it is declared in. A value type on a class has a lifetype that is exactly the same as the class it is declared in, requiring almost no work by the garbage collector. It's more complicated though, i'd refer to @JonSkeet's book "C# In Depth" or his article "Memory in .NET" for a more concise explenation.

    Advantages:

    A value type does not need extra garbage collection. It gets garbage collected together with the instance it lives in. Local variables in methods get cleaned up upon method leave.

    Drawbacks:

    1. When large set of values are passed to a method the receiving variable actually copies so there are two redundant values in memory.

    2. As classes are missed out.it losses all the oop benifits

    Reference type:

    Holds a memory address of a value not value

    Example:

    Class

    Storage:

    Stored on heap

    Advantages:

    1. When you pass a reference variable to a method and it changes it indeed changes the original value whereas in value types a copy of the given variable is taken and that's value is changed.

    2. When the size of variable is bigger reference type is good

    3. As classes come as a reference type variables, they give reusability, thus benefitting Object-oriented programming

    Drawbacks:

    More work referencing when allocating and dereferences when reading the value.extra overload for garbage collector

提交回复
热议问题