C#, Copy one bool to another (by ref, not val)

Kieran picture Kieran · Sep 16, 2009 · Viewed 20.5k times · Source

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 separate bool with a value of false. If I subsequently change a, it will have no effect on b. Is it possible to make a = b by ref? How would I do that?

Many thanks

Answer

Reed Copsey picture Reed Copsey · Sep 16, 2009

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