Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does passing a value type in an "out" parameter cause the variable to be boxed?

I'm aware that boxing and unboxing are relatively expensive in terms of performance. What I'm wondering is:

Does passing a value type to a method's out parameter cause boxing/unboxing of the variable (and thus a performance hit)? Can the compiler optimize this away?

  int number;
  bool result = Int32.TryParse(value, out number);
like image 883
Justin Morgan Avatar asked Jan 26 '11 16:01

Justin Morgan


1 Answers

As others have pointed out, there's no boxing here. When you pass a variable as an argument corresponding to an out or ref parameter, what you are doing is making an alias to the variable. You are not doing anything to the value of the variable. You're making two variables represent the same storage location.

Boxing only happens when a value of a value type is converted to a value of a reference type, and there's no conversion of any kind in your example. The reference type must of course be System.Object, System.ValueType, System.Enum or any interface. Usually it is pretty clear; there's an explicit or implicit conversion in the code. However, there can be circumstances where it is less clear. For example, when a not-overridden virtual method of a struct's base type is called, there's boxing. (There are also bizarre situations in which certain kinds of generic type constraints can cause unexpected boxing, but they don't usually come up in practice.)

like image 120
Eric Lippert Avatar answered Oct 01 '22 03:10

Eric Lippert