18

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

4
  • 2
    Refactor to only reference a?? Sep 16, 2009 at 19:00
  • 5
    Can you explain the scenario in which, you will need such a thing? Sep 16, 2009 at 19:01
  • why would you want to do this? if you give more details perhaps someone will a way to do what you really want.
    – Zack
    Sep 16, 2009 at 19:02
  • 1
    you have to use pointers, but why programming in a managed environement then (.NET)...
    – manji
    Sep 16, 2009 at 19:06

8 Answers 8

42

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 
2
  • 3
    Indeed. Though I can't help wondering why such a thing is necessary in the first place...
    – Noldorin
    Sep 16, 2009 at 19:20
  • 5
    Reference types guarantee that the object being referred to will live at least as long as the reference. Value types, offering no such guarantee, are often stored on the stack, and disappear as soon as execution leaves their declaration scope. Allowing one to create a persistent and promiscuous reference to a value type would require that the computer copy the variable off the stack before its scope exits, pointing the reference at the new copy; there are in theory a number of ways the system could do that, but all of them would add huge overhead any time any variable leaves scope.
    – supercat
    Oct 6, 2011 at 17:02
19

Thanks to @Reed for his answer (+1)! He encouraged me to a more "generic" solution! :)

public class ValueWrapper<T> where T : struct
{
    public T Value { get; set; }
    public ValueWrapper(T value) { this.Value = value; }
}
3
  • Is there any reason to make Value a property rather than a field? One can use things like Interlocked.CompareExchange on fields, but not on properties. Perhaps not relevant for ValueWrapper<System.Boolean>, but certainly relevant for ValueWrapper<System.Integer>.
    – supercat
    Apr 24, 2012 at 21:08
  • @supercat I'm using this field in the DataBinding, because it must be a property Jul 5, 2012 at 18:43
  • I can see that limitations of DataBinding might compel the use of a property, though public fields do offer many advantages in cases where a property isn't explicitly required. Perhaps a reasonable approach would be to expose a public Value field and a ValueAsProperty property backed thereby?
    – supercat
    Jul 5, 2012 at 19:02
15

Small extension to Andrey's answer... this allows you to assign it to whatever type you want in the end directly. So:

        ValueWrapper<bool> wrappedBool = new ValueWrapper<bool>(true);

        bool unwrapped = wrappedBool;  // you can assign it direclty:

        if (wrappedBool) { // or use it how you'd use a bool directly
            // ...
        }

public class ValueWrapper<T>
{

    public T Value { get; set; }

    public ValueWrapper() { }

    public ValueWrapper(T value) { 
        this.Value = value; 
    }

    public static implicit operator T(ValueWrapper<T> wrapper)
    {
        if (wrapper == null) {
            return default(T);
        }
        return wrapper.Value;
    }

}

7

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;
}
1

So I'm guessing you are needing to pass a reference a bool, that you cannot wrap with a 'BoolWrapper' class, because the bool lives some place that you cannot or do not wish to modify.

It can be done!

First declare what any bool reference will look like

/// <summary> A reference to a bool.</summary>
/// <param name="value">new value</param>
/// <returns>Value of boolean</returns>
public delegate bool BoolRef(bool? value = null);

Now you can make a reference to myBool like this

    bool myBool; // A given bool that you cannot wrap or change
    private bool myBoolRef(bool? value) {
        if (value != null) {
            myBool = (bool)value;
        }
        return myBool;
    }

And use it like this:

    void myTestCaller() {
        foo(myBoolRef);
    }
    void foo(BoolRef b) {
        bool c = b(); // get myBool
        b(true); // set myBool to true
    }

The same trick works for other value types such as int

1
  • I would be interested to know why this is downvoted. I have found this solution useful in several cases.
    – James
    Nov 23, 2015 at 11:27
0

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

3
0

I had a case where I wanted one class to change another class' bool - please note that there are better ways to handle this situation but this is a proof of concept using Actions.

public class Class1 
{
    bool myBool { get; set; }
    void changeBoolFunc(bool val) { myBool = val; }
    public Class1() 
    {
        Action<bool> changeBoolAction = changeBoolFunc;
        myBool = true; 
        Console.WriteLine(myBool);    // outputs "True"
        Class2 c2 = new Class2(changeBoolAction);
        Console.WriteLine(myBool);    // outputs "False"
    }
}
public class Class2
{
    public Class2(Action<bool> boolChanger) { boolChanger(false); }
}
void Main()
{
    Class1 c1 = new Class1();
}
-3

Just use the flags as Nullable<bool> or bool? and set those in the struct that's passed to the generic method. The ValueWrapper<T> class above is essentially exactly what Nullable<T> does.

1
  • 4
    Nullable<T> is still a value type, see the definition: public struct Nullable<T> where T : struct
    – rfcdejong
    Oct 26, 2012 at 13:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy