From the perspective of memory layout, let's talk about the value type and reference type!

Source: Internet
Author: User
A deep understanding of value type and reference type is the key to. Net developers' long-term success. The following describes the value type and reference type from the perspective of memory layout:
Memory Structure of Value Type:

Memory Structure of the reference type:


An instance of the reference type has two additional fields, syncblockindex and rtti pointer, pointing to a method table structure, therefore, the description of methodtableptr and typeobjectptr are both acceptable. The first version of the book "CLR via C #" marks methodtableptr, and the second version marks typeobjectptr, jeffery thinks typeobjectptr is more accurate.
Besides the object and valuetype types, the value type cannot inherit any other types and cannot be used as the base class of other value types. Therefore, no method table pointer is required in general! When you need to call methods inherited from objects or valuetype, you need a method table pointer. In this case, you need to pack the value type!
Let's look at an example:
Public struct
{
Public overrid string tostring ()
{
Return "A ++ ";
}
}

static void main (string [] ARGs)
{< br> A = new A ();
. tostring (); // it will not be boxed at this time, because the C # compiler finds that struct a overwrites the tostring method, so it will generate an il command to directly call tostring, moreover, it is impossible for a type to inherit from struct a, so the compiler can determine that there will be no polymorphism, so no method table pointer or packing is required!
. getType (); // The box is packed here. Because struct a does not implement the GetType method, you need to call the inherited GetType method. In this case, you need a method table pointer to access the method table, in this case, we need to get it through packing!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.