Re: Passing arguements by reference

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance



"Andrew Bullock" <andrewREMOVEbullockTHIS@xxxxxxxxxxxxxxxxxxx> wrote in message
news:oIkMf.18500$gB4.17084@xxxxxxxxxxxxxxxxxxxxxxx
Hi,

I have two classes, A and B,

B takes an A as an argument in its constructor:


A a1 = new A();
B b = new B(a1);

///

A a2;
public B(A aa)
{
a2 = aa;
}




However, I figured that I could reduce memory usage and increase performance by passing aa by
reference.

That would be an incorrect assumption.
In the code above, you are already passing a reference to an A object in to the constructor for B.
In C#, you never directly pass objects as parameter, instead you pass references to objects.
Thus, in class B, you only pay for the cost of a reference.
The net effect is that a1 and a2 in your code both are references to the same A object.

If you don't wish to share the object, then you need to clone it and save the reference to the
clone.
Of course, since you mentioned reducing memory usage, this is obviously not a problem in this case

Hope this helps

Bill

<snip>


.



Relevant Pages

  • Re: Creating a reference to an object
    ... Clone is a specific reference to the Clonemethod ... Since a constructor doesn't "return" anything, it's always of the type being constructed. ... MemberwiseClone(), but that only ever makes a shallow copy. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Creating a reference to an object
    ... Clone is a specific reference to the Clonemethod ... you are cloning ... such as if you were to make a copy constructor ... ICloneable you can make another copy of a reference or tracking ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Object recreating itself as a different class type ?
    ... which is a reference to the instance or ... Under the register convention, Self behaves as if it were declared before ... A value of False in the flag parameter of a constructor call indicates that ... A value of False in the flag parameter of a destructor call indicates that ...
    (alt.comp.lang.borland-delphi)
  • Re: iexplorer halts on exit when ActiveXObject has been used
    ... > that is a constructor and destructor, ... > The var 'something' is a reference to the object created by use ... If the property has the DontDelete attribute, ... >> So you might expect that the property of the global/Variable object ...
    (comp.lang.javascript)
  • Re: How to pass information, classes between forms in Windows Application mode
    ... parametricized or parameter constructor, ... Form2: Form1 as you discuss below and as I further comment below. ... You're passing a reference to the object. ...
    (microsoft.public.dotnet.languages.csharp)