Why does the tostring () method not involve packing and unpacking?

Source: Internet
Author: User

Here is an algorithm question: convert an integer into a string and output it.

So think of int32.tostring ().

In the. NET source code, only the following results are obtained:

 

 public override string ToString()
{
return Number.FormatInt32(this, null, NumberFormatInfo.CurrentInfo);
}

[MethodImpl(MethodImplOptions.InternalCall)]
public static extern string FormatInt32(int value, string format, NumberFormatInfo info);



 

 

 

Formatint32It is implemented by the CLR underlying layer ..

Today, I didn't get an answer to the internal implementation of Google int32.tostring (), but I found this question: why does the tostring () method not involve packing or unpacking?

 

Actually, it is clearly written in CLR via C # (CLR via C #3 edition p139)

Calling tostring in the call to tostring, P1 doesn't have to be boxed. At first, you 'd
Think that P1 wowould have to be boxed because tostring is a virtual method that is
Inherited from the base type, system. valuetype. Normally, to call a virtual method,
The CLR needs to determine the object's type in order to locate the type's Method
Table. Since P1 is an unboxed value type, there's no type object pointer. However,
Just-in-time (JIT) compiler sees that point overrides the tostring method, and it emits
Code that calltostring directly (non‑ally) without having to do any boxing.
Compiler knows that polymorphism can't come into play here since point is a value
Type, and no type can derive from it to provide another implementation of this virtual
Method. Note that if point's tostring method internally callbase. tostring (), then
The Value Type instance wocould be boxed when calling system. valuetype's tostring
Method.

Although int32 inherits from system. valuetype (class), It override the tostring () of the base class. int32 does not need to be loaded as an object. Int32 is valuetype.

Through Google, I realized that struct can also inherit classes ....

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.