Jump to content

fire event when boolean sets to false

- - - - -

  • Please log in to reply
2 replies to this topic

#1
salmon rushload

salmon rushload

    Newbie

  • Members
  • Pip
  • 4 posts
hi all,

i should be able to figure this out. ive tried the msdn documation and searching google, but this whole events delegates thing still has me confused.

essentially what i want to to is fire an event when a boolean variable in my class gets set to true. example:


public class MyClass

{

    private bool MyBool = false; 


    public void SetMybool(bool b)

    {

        MyBool = b; 

    }

}


public class program

{

    public static void Main()

    {

        MyClass NewClass = new MyClass();

        NewClass.SetMybool(true); //// would like to see an event fired here ....

    }


}

help????

#2
sam_coder

sam_coder

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 372 posts
ok, so, have you considered using a property? Ultimately, its the same difference, but it looks nicer.

And delegates arent so bad, they're just type-safe function pointers.

Consider something like the following...

public class MyClass

{


	public MyClass() {

		MyBoolSet += OnMyBoolSet;

		return;

	}


	public delegate void bool_handler(bool value);


	public event bool_handler MyBoolSet;


	private bool m_bool = false; 

	

	public bool MyBool {

		get { 

			return m_bool; 

		}

		set { 

			m_bool = value; 

			MyBoolSet(m_bool); 

		}

	}


	private void OnMyBoolSet(bool value) {

		//You'll want this here to prevent a null reference exception, but ultimately, you may not do any internal handling.  Or maybe you will, who knows...

		return;

	}


}


public class program

{

    public static void Main()

    {

        MyClass NewClass = new MyClass();

	NewClass.MyBoolSet += OnMyBoolSet;

        NewClass.MyBool = true; //// would like to see an event fired here ....

    }


	static void OnMyBoolSet(bool value) {

		Console.WriteLine("the boolean value was set to: {0}", value);

	}




I havent tested that, but It should work. or with very minor tweaking. anyways,

this might be a good place to start:
Delegates (C#)

#3
salmon rushload

salmon rushload

    Newbie

  • Members
  • Pip
  • 4 posts
thanks sam_coder, just what i needed.

it seems simple when you explain it like that. all the other solutions i was trying to implement were involving EventArgs and stuff like that. awesome.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users