Passing Struct by Ref via Class Constructor

  • Thread starter Thread starter Danny Tan
  • Start date Start date
D

Danny Tan

Hi folks,

I'm a newbie, trying to pick up C#. This is something, I'm currently working
on for my assignment.

I understand that struct is a "value type". And I'm trying to pass a struct
by reference while instantizing a new Class object.

I can't seems to be able to get it to work. Even after using "ref", it is
still "passed-by-value".

Where did I go wrong?

Regards,
Danny

-------------------------------------------

public struct Bin
{
int j, k;

public Bin(int i, int j)
{
// --- some codes
}
//--- some codes
}

public ClassA
{
Bin bin;

// --- constructor
public ClassA(ref Bin x)
{
bin = x;
}
// --- some codes to change the values of bin
}

public class DriverClass
{
static void Main()
{
Bin bin = new Bin(value1, value2)

// --- instantiate new object passing struct by reference
ClassA NewObject = new ClassA(ref bin);
}
}
 
Danny Tan said:
I'm a newbie, trying to pick up C#. This is something, I'm currently working
on for my assignment.

I understand that struct is a "value type". And I'm trying to pass a struct
by reference while instantizing a new Class object.

I can't seems to be able to get it to work. Even after using "ref", it is
still "passed-by-value".

No, it's passed by reference. However, when you assign to the bin
member variable, that assignment is done by value - and there's no way
of avoiding that.

It looks like you basically want reference semantics for Bin rather
than value semantics - so why not make Bin a class rather than a
struct? Alternatively, create a wrapper class for Bin which lets you
change the value within it.
 
In the context of the constructor, 'x' is byref. So anything you do to 'x'
will be reflected in the caller.

However, the line: bin=x

Just follows the regular rules with structs. It makes a copy of 'x' and
puts it in bin. 'x' is still by ref. But that doesn't mean that 'bin' is.
bin is a separate instance of the struct.
 
ic. Thanks for the info!



Marina said:
In the context of the constructor, 'x' is byref. So anything you do to 'x'
will be reflected in the caller.

However, the line: bin=x

Just follows the regular rules with structs. It makes a copy of 'x' and
puts it in bin. 'x' is still by ref. But that doesn't mean that 'bin'
is. bin is a separate instance of the struct.
 
Back
Top