shared int reference?

  • Thread starter Thread starter Alex Leduc
  • Start date Start date
A

Alex Leduc

I'd like to know how one shares an int variable across different ocjects
(of different classes) without pointers.

public class ClassA {
public int n;
public ClassA(int N) {
n = ???
n++;
}
}

public class ClassB {
public int n = 0;
public ClassA = new ClassA(n);
}

If I increment n in the instance of ClassA, I would like the parent
ClassB's instance to have it's "n" varable to have the same value.

Alex
 
I'd like to know how one shares an int variable across different
ocjects (of different classes) without pointers.

public class ClassA {
public int n;
public ClassA(int N) {
n = ???
n++;
}
}

public class ClassB {
public int n = 0;
public ClassA = new ClassA(n);
}

If I increment n in the instance of ClassA, I would like the parent
ClassB's instance to have it's "n" varable to have the same value.

In general, you can use the 'ref' parameter:

public ClassA(ref int N) { ... }

and

public ClassA = new ClassA(ref n);

BTW, I've never seen ref's used on a constructor - I'm not sure if this
is valid or not. Then again, I've not seen anything that says it can't
be done (haven't tried it.)

-mdb
 
ref will not allow you to share the reference across objects the way a
pointer would do, because if you assign the ref to a field of the target
object, you "copy" the value instead of sharing the reference.

If you want to share an int value, you have to create a small object with an
int property (IntCounter would be a good class name for this). Then, you can
share the object and the trick is done. But there is no way to share an int
directly, at least not in managed code.

Bruno.
 
Michael said:
In general, you can use the 'ref' parameter:

public ClassA(ref int N) { ... }

and

public ClassA = new ClassA(ref n);

BTW, I've never seen ref's used on a constructor - I'm not sure if this
is valid or not. Then again, I've not seen anything that says it can't
be done (haven't tried it.)

-mdb

The problem is that the assignment operator copies the value of N into n

public ClassA(ref int N)
{
n = N;
}
 
You can also allocate an array with a single entry (new int[1]) and share
it.

Bruno
 
The problem is that the assignment operator copies the value of N into n

public ClassA(ref int N)
{
n = N;
}

Yeah sorry I didn't understand your original question. You can't really
share something between multiple objects (unless its the same TYPE of
object, in which case you can use a static variable.)

-mdb
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top