Pass-by-reference in Method parameter list--what exactly is being passed?

Aug 1 2007 5:51 AM

I am an experienced C and C++ programmer (managed and traditional).  I understand references are being passed in a method parameter list, but I wouild like to know a little more about pass-by-reference vs pass-by-value when objects are being passed.

 

consider:

 

public Class MyClassOne {

  public int myintone;

  public MyClassOne (MyClassTwo MC2) // forward reference

    { // do something to change MyClassTwo}

  public void MyFunctionOne (int i, MyClassTwo MCT) {

   // do we need 'ref' before MyClassTwo MCT?

 

     MyClassTwo LocalMyClassTwo; //*&* compiler error?do you need a new()here?

     LocalMyClassTwo = MCT; //! note

     // do stuff to change MCT

}

 

public Class MyClassTwo {

//stuff here, including 'normal constructor' (C++ term)

}

 

static void Main()

{

     MyClassTwo MC2 = new MyClassTwo();

     MyClassOne MC1 = new MyClassOne (MC2);

 

     MC1.MyFunctionOne(10,MC2)

    // OR, DO WE NEED THIS VERSION?

    // MC1.MyFunctionOne(10,ref MC2);

 

}

 

From the above, without belabouring the point, I think you can see my concern:  aside from the 'compile error' at *&* above, (I'm not sure it will compile, but that's minor), my real question is whether "MyFunctionOne" is working on a copy of the reference to MC2 (I assume not, otherwise the issue is complicated by whether a shallow copy or a deep copy is being made), and, regardless, whether MC2 will be changed by MyFunctionOne or not.  If MC2 is being changed, why don't we (or do we?) need the 'ref' keyword before it?

 

Thank you.

 

Fran

 


Answers (13)