views:

483

answers:

4

Hi folks.

I am at a brick wall here. Is it possible to copy one bool to the ref of another. Consider this code . . .

        bool a = false;
        bool b = a;

b is now a totally seperate bool with a value of false. If I subsequently change a, it will have no effect on a. Is it possible to make a = b by ref ?How would I do that ?

Many thanks

A: 

A bool is a value type and cannot be copied by reference.

Matt Wrock
bool is just a shortcut for System.Boolean. They're identical.
Reed Copsey
a C# bool is a System.Boolean. They are the same and both are value types.
Zack
Yes, and System.Boolean is a value type. See: http://msdn.microsoft.com/en-us/library/system.boolean.aspx
Adam Hughes
+11  A: 

No. Since bool is a value type, it will always be copied by value.

The best option is to wrap your bool within a class - this will give it reference type semantics:

public class BoolWrapper
{
     public bool Value { get; set; }
     public BoolWrapper (bool value) { this.Value = value; }
}

BoolWrapper a = new BoolWrapper(false);
BoolWrapper b = a;
b.Value = true; 
 // a.Value == true
Reed Copsey
Indeed. Though I can't help wondering why such a thing is necessary in the first place...
Noldorin
A: 

this may not be what you want, but if your scenario were such that you wanted a function that you called to modify your local boolean, you can use the ref or out keyworkd.

bool a = false;

F(ref a);
// a now equals true

...

void F(ref bool x)
{
x = true;
}
Zack
A: 

the scenario is experimental really.

I am creating a version of John Conway's Game of Life.

http://en.wikipedia.org/wiki/Conway%27s%5FGame%5Fof%5FLife

I am trying to optimise it as much as possible. For each cell in the grid, it is either on or off (bool). This is determined by the state of its neighbours (the 8 cells immediately around the current cell). So I thought I would remember the neighbours rather than have to work them out on each pass.

To represent the live state of my cells, I am using a 2d array of bools. When I create the neighbours, I want each bool in the neighbours array to point to the relevant cell in the overall grid. (by ref, not value).

Does this make sense ?

Eh, it's not hard to simply recompute them. You want to really blow your mind? Implement Bill Gosper's HashLife algorithm. You can get _trillions_ of generations per second!
Eric Lippert