mingpepe
mingpepe

Reputation: 559

Why is ref needed in this case?

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.

Upvotes: 0

Views: 104

Answers (1)

UserControl
UserControl

Reputation: 15149

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.

Upvotes: 2

Related Questions