1

How to avoid the boxing during the value type parameter passing in .NET?

Is the use of the ref keyword is the only way? E.g. in this way:

using System;

namespace myprogram
{
    struct A {
        public static void foo(ref A a) {}
    }

    class Program {
        static void Main(string[] args) {
            A a = new A();
            A.foo(ref a);
        }
    }
}

Or are there any other ways to accomplish this?

I found this answer. It explains what operations should I avoid in order to avoid boxing, but it does not tell how I can do that.

Also, I am reading the CLR via C# book which also misses the point of how to pass the value type without boxing (or at least after reading the book I did not find the information).

qqqqqqq
  • 1,831
  • 1
  • 18
  • 48
  • 1
    There is no boxing, whether you use ref or not. It only occurs when it gets converted to an object, that doesn't happen in this snippet. – Hans Passant Nov 23 '19 at 15:46

1 Answers1

1

You can use your method without the keyword "ref" because ref means, that the method gets the address of value type variable, while without this keyword the method just gets a copy of the variable. In any case, if you will send a value type to any method, which takes a value type, you will not get the boxing. To verify this, it is the Msil output, which cs compiler will compile for your current program, if you will remove the keyword "ref".

IL_0001: ldloca.s 0
IL_0003: initobj myprogram.A
IL_0009: ldloc.0
IL_000a: call void myprogram.A::foo(valuetype myprogram.A)
IL_000f: nop
IL_0010: ret

As expected, we are not getting any boxing.

YVEF
  • 139
  • 1
  • 9