John Brown <no_spam@_nospam.comwrote:
>Can someone confirm whether the following technique is now broken in .NET
2.0 (it worked in 1.1).
// Avoid boxing and losing our return value
object inoutCancel = false;
That's not avoiding boxing at all - it's just boxing it earlier!
Thanks the feedback. In actuality however, that was a quote from Chris Sells
who's probably more widely known in C++ circles (which is my own
background). You can read what he said here if you're interested (just
search for "avoid boxing" and see the paragraph that immediately follows
http://msdn.microsoft.com/library/en...asp?frame=true
In 1.1, when an out/ref parameter which was originally a boxed value
type changes, the value in the box changes. In 2.0, the element in the
array is set to a new boxed value. Here's a small app to demonstrate
this:
using System;
using System.Reflection;
class Test
{
public static void SetToFive (out int x)
{
x = 5;
}
static void Main()
{
MethodInfo mi = typeof(Test).GetMethod("SetToFive");
object parameter = 0;
object[] parameters = new object[]{parameter};
mi.Invoke (null, parameters);
Console.WriteLine ("After invocation:");
Console.WriteLine ("parameter={0}", parameter);
Console.WriteLine ("parameters[0]={0}", parameters[0]);
}
}
On .NET 1.1, the output is:
After invocation:
parameter=5
parameters[0]=5
On .NET 2.0, the output is:
After invocation:
parameter=0
parameters[0]=5
This change breaks existing code however. Maybe the original behaviour was a
problem and had to be corrected for some reason but at first glance this
change seems totally absurd and counterintuitive. The array contains a
reference to an object which is being passed as an "out" parameter. That
object should therefore be changed and it's potentially dangerous to do
anything else (or potentially error prone anyway since the programmer may be
storing the original reference somewhere which will no longer point to the
updated value - any such references must therefore be updated after each
call) . More importantly perhaps, how do they justify replacing the original
array element with another. It's syntactically inconvenient as well since
you can no longer create the array on the fly (in the function call) because
you now have to keep it around in order to index into it afterwards. Even
worse, you have to hardcode the index of the parameter itself or otherwise
store it somewhere so you can index into the array afterwards (not only
ugly, but the index will have to be changed if the parameter's ordinal
position ever changes). This is all brutal IMO and I'd like to know what the
justification was (assuming it wasn't a mistake - they must have had a
legitimate reason for it otherwise). Anyway, thanks again.