Today I came across a post that asked “Are reference types true?” The author was, I believe, trying to make the point that the behavior of reference types passed to methods may behave in a way you don't expect. (Click the link above to see the code sample in question.)
In this particular case, the expected output is 20, not 10. The value 10 would be true only if the valhold class was passed into method1 using the "ref" keyword. The default behavior of object passing in .NET is to pass a copy of the object in the case of value types or, in the case of reference types, to pass a copy of the object reference (or pointer, not the actual object reference itself). Since method1 in the example takes a valhold class as-is (by copying the reference to the reference), you can still manipulate the contents of the original object. However, if you replace the original object in the method body, then you are now dealing with a new object and any changes will not be made to the original object.
Here are a couple of good articles explaining how it all works:
Copying, Cloning, and Marshalling in .NET
http://www.ondotnet.com/pub/a/dotnet/2002/11/25/copying.html
C# Programmer's Reference: Passing Parameters
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csref/html/vclrfpassingmethodparameters.asp
UPDATED:
Carl and Rory from DotNetRocks Radio give you a entertaining overview from their VB.NET Master Class on objects in .NET - this link is great if you need a visual explanation of how it all works (especially useful for those of you with a prior VB background)
http://www.franklins.net/dotnetrocks/dnrvideos.aspx
Posted
11-07-2003 1:11 PM
by
paul.laudeman