VBForums >
.NET >
C# > [RESOLVED] Confirmation: Are objects always passed as ByRef?
Click to See Complete Forum and Search --> : [RESOLVED] Confirmation: Are objects always passed as ByRef?
dee-u
Mar 26th, 2006, 09:31 PM
Just want confirmations since this is to be the case...
jmcilhinney
Mar 26th, 2006, 09:55 PM
In C# you have to declare the argument using the "ref" keyword, otherwise parameters will be passed by value. Note that the implications of passing by reference and by value are slightly different for value types and reference types. It is the variable that you are passing by value or by reference. With value types the variable contains the object while with reference types the variable contains a reference to the object.
dee-u
Mar 26th, 2006, 10:04 PM
Why is it tha when I passed a custom collection of mine as a parameter to a method then added values to that collection then the added values appears to the passed collection?
It is the same scenario as I described here (http://www.vbforums.com/showthread.php?t=395334)...
Kasracer
Mar 26th, 2006, 10:59 PM
Um... that's a VB6 question. Why would that have anything to do with C# or .Net? :confused:
Shuja Ali
Mar 27th, 2006, 12:40 AM
Why is it tha when I passed a custom collection of mine as a parameter to a method then added values to that collection then the added values appears to the passed collection?As already mentioned by JM, when you pass reference types you are actually passing the reference of the object unlike value types where the type holds the values too. So as collection is a reference type when you pass it to another method and do some changes to it, you are actually changing the same object because both contain the reference to the same object.
jmcilhinney
Mar 27th, 2006, 12:55 AM
That's exactly why I specified that you are passing the VARIABLE by reference or by value, not the object. When you pass a reference type object by value you are passing a copy of the variable. That means you have two variables that refer to the same object. If you make changes to the object via that reference then that change will be reflected in the original. If you assign a new object to that variable then that change will not be reflected, because the original variable still refers to the original object. If you actually want to make changes to a reference type object past as a parameter without those changes being reflected in the original then you need to create a copy of the actual object and pass a reference to that. Why you would want to do this though I don't know.
dee-u
Mar 27th, 2006, 10:37 PM
Hmmmnnn... Does it mean my business object is also of reference type?
jmcilhinney
Mar 27th, 2006, 10:56 PM
Every class is a reference type and every structure is a value type.
dee-u
Mar 27th, 2006, 10:57 PM
Ahhh... Thanks again! :thumb:
vbforums.com
Copyright Internet.com Inc., All Rights Reserved.