1

I’m passing a bool to a method in another class by reference, so that I can change it (-the original argument) from within the method.

I also want an event (which is subscribed to by that method) to be able to change it.

Doing this:

class myCheckBox : CheckBox
{
    bool b1;
    public myCheckBox(ref bool b)
    {
        b1 = b;
        this.CheckedChanged += new EventHandler(myCheckBox_CheckedChanged);
    }

    void myCheckBox_CheckedChanged(object sender, EventArgs e)
    {
        b1 = Checked;
    }
}

doesn’t help, since b1 is only a copy of b.

Is there any way of doing: ref b1 = ref b; ? if not, how do I solve this?

(The examples are only to explain the question.)

ispiro
  • 26,556
  • 38
  • 136
  • 291
  • Maybe you could use [boxing](http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx) for this. Or use the return value, anyway i think its rather strange what you are trying to do and you should try to avoid it. – dowhilefor Oct 27 '11 at 22:14
  • @dowhilefor What I’m trying to do is create an automated checkbox class that will change the bool associated with it. – ispiro Oct 27 '11 at 22:34

4 Answers4

4

You'd typically pass an argument to your event handler that has a boolean property that can be modified by the event handler:

public class MyEventArgs : EventArgs
{
    public bool Value { get; set; }
}

public class MyClass
{
    public void method1(ref bool b)
    {
        MyEventArgs e = new MyEventArgs()
        {
            Value = b
        };
        eventMethod(e);

        b = e.Value;
    }

    void eventMethod(MyEventArgs e)
    {
        e.Value = false;
    }
}

You may also want to take a look at the standard event handler pattern established in .NET: How to: Publish Events that Conform to .NET Framework Guidelines (C# Programming Guide)

Joel C
  • 5,547
  • 1
  • 21
  • 31
  • What you're trying to do violates the OOP principle of encapsulation. You're letting one class change the internal state of another class. You also don't typically wire up an event handler to an event in the same class; you can call your own methods directly. A cleaner approach would be to have the class that actually contains the boolean field subscribe to the `CheckedChanged` event and update itself. – Joel C Oct 28 '11 at 14:10
1

Pass the class containing the field, a string denoting it, and save them instead of b1. Then use reflection.

See How to create a reference to a value-field

Community
  • 1
  • 1
ispiro
  • 26,556
  • 38
  • 136
  • 291
0

Make b1 a public field of your class.

Or a private one, with a property with a public getter and a public setter.

Otiel
  • 18,404
  • 16
  • 78
  • 126
0

Well when I copied the code intyo a Console app (had to change to static functions and var b1 of course) it works as you want, when called from Main:

bool b = true;
method1(ref b);
Console.writeLine(b1);

prints 'false'....

Aaron Gage
  • 2,373
  • 1
  • 16
  • 15