0

I was looking at the reference source and found NumberToInt32:

http://referencesource.microsoft.com/#mscorlib/system/number.cs,a2e15b1a0fe0c25c

[System.Security.SecuritySafeCritical]  // auto-generated
internal unsafe static Int32 ParseInt32(String s, NumberStyles style, NumberFormatInfo info) {

    Byte * numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
    NumberBuffer number = new NumberBuffer(numberBufferBytes);
    Int32 i = 0;

    StringToNumber(s, style, ref number, info, false);

    if ((style & NumberStyles.AllowHexSpecifier) != 0) {
        if (!HexNumberToInt32(ref number, ref i)) { 
            throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
        }
    }
    else {
        if (!NumberToInt32(ref number, ref i)) {
            throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
        }
    }
    return i;           
}

[System.Security.SecuritySafeCritical]  // auto-generated
private unsafe static Boolean NumberToInt32(ref NumberBuffer number, ref Int32 value) {

    Int32 i = number.scale;
    if (i > Int32Precision || i < number.precision) {
        return false;
    }
    char * p = number.digits;
    Contract.Assert(p != null, "");
    Int32 n = 0;
    while (--i >= 0) {
        if ((UInt32)n > (0x7FFFFFFF / 10)) {
            return false;
        }
        n *= 10;
        if (*p != '\0') {
            n += (Int32)(*p++ - '0');
        }
    }
    if (number.sign) {
        n = -n;
        if (n > 0) {
            return false;
        }
    }
    else {
        if (n < 0) {
            return false;
        }
    }
    value = n;
    return true;
}

What is the reason that NumberToInt32 uses the ref keyword to number? The number seems unchanged in the function.

Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
mingpepe
  • 489
  • 5
  • 10
  • 2
    Considering it's run in an unsafe context and very low level functions, they're trying to conserve memory or perf reasons. Those buffers are on the stack and they wouldn't want to copy those around. – Jeff Mercado Apr 17 '16 at 05:23
  • The NumberBuffer declaration is essential. Class and Structure objects are handled [differently](https://msdn.microsoft.com/en-us/library/8b0bdca4.aspx). See also [this](http://stackoverflow.com/questions/7171842/does-passing-reference-types-using-ref-save-memory) SO question. – Jeroen Heier Apr 17 '16 at 05:36

1 Answers1

2

If you look at NumberBuffer source you'll notice the structure has five fields making it pretty large to be copied. So the idea to use ref here is just speed optimization. You don't have to modify any ref parameters just because you can.

UserControl
  • 14,766
  • 20
  • 100
  • 187