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

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

    This is probably wrong in esoterical ways, but, to make it simple:

    Value types are values that are passed normally "by value" (so copying them). Reference types are passed "by reference" (so giving a pointer to the original value). There isn't any guarantee by the .NET ECMA standard of where these "things" are saved. You could build an implementation of .NET that is stackless, or one that is heapless (the second would be very complex, but you probably could, using fibers and many stacks)

    Structs are value type (int, bool... are structs, or at least are simulated as...), classes are reference type.

    Value types descend from System.ValueType. Reference type descend from System.Object.

    Now.. In the end you have Value Type, "referenced objects" and references (in C++ they would be called pointers to objects. In .NET they are opaque. We don't know what they are. From our point of view they are "handles" to the object). These lasts are similar to Value Types (they are passed by copy). So an object is composed by the object (a reference type) and zero or more references to it (that are similar to value types). When there are zero references the GC will probably collect it.

    In general (in the "default" implementation of .NET), Value type can go on the stack (if they are local fields) or on the heap (if they are fields of a class, if they are variables in an iterator function, if they are variables referenced by a closure, if they are variable in an async function (using the newer Async CTP)...). Referenced value can only go to the heap. References use the same rules as Value types.

    In the cases of Value Type that go on the heap because they are in an iterator function, an async function, or are referenced by a closure, if you watch the compiled file you'll see that the compiler created a class to put these variables, and the class is built when you call the function.

    Now, I don't know how to write long things, and I have better things to do in my life. If you want a "precise" "academic" "correct" version, read THIS:

    http://blogs.msdn.com/b/ericlippert/archive/2010/09/30/the-truth-about-value-types.aspx

    It's 15 minutes I'm looking for it! It's better than the msdn versions, because it's a condensed "ready to use" article.

提交回复
热议问题