1

Here's an explanation of what I'm trying to achieve:

I have a textbox that I'm using as a 'debug', or 'information' window on my form. What I would like to do is have any classes that I create throw an event when it has information to post to the debug window, and then have the text window subscribe to said event, and post each time something new comes in. I'm trying to make it so that my classes don't need knowledge of the textbox but still have the capability to pass all of the information to the text box.

Is it possible to have a 'shared' event among classes (perhaps using an interface) so that I only need to subscribe to that one event and it will pull from all classes that throw the event?

For a visual, it would basically look like this:

Public delegate void DebugInfo(string content)

Class foo1
{
   event DebugInfo DebugContentPending

   public void bar()
   {
      DebugContentPending("send this info to the debug window")
   }
}

Class foo2
{
   event DebugInfo DebugContentPending

   public void bar()
   {
      DebugContentPending("send this info to the debug window")
   }
}


Class SomeClass
{
    public void SomeMethod()
    {
       DebugContentPending += new DebugInfo(HandleContent);  //gets events from foo1 and foo2
    }

    public void HandleContent(string content)
    {
       //handle messages
    }
}

is this possible or am I off my rocker?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
David Torrey
  • 1,335
  • 3
  • 20
  • 43

1 Answers1

4

Most likely you don't need events.

class DebugLogger
{
    public DebugLogger(TextBox textBox)
    {
        this.TextBox = textBox;
    }

    public TextBox TextBox { get; private set; }

    public static DebugLogger Instance { get; set; }

    public void Write(string text)
    {
        this.TextBox.Text += text;
    }
}

Initialization:

DebugLogger.Instance = new DebugLogger(textBox1);

Usage:

DebugLogger.Instance.Write("foo");

Notice that code is not thread safe. See Automating the InvokeRequired code pattern and related for more information.

Community
  • 1
  • 1
abatishchev
  • 98,240
  • 88
  • 296
  • 433
  • one question: what does this give me over just making a public static class? – David Torrey Feb 10 '13 at 08:12
  • @DavidTorrey: You can't instantiate it but you need to. Also you don't have a reference to an instance of the form/textbox from static constructor if any you would imagine to declare. You're getting such instance outside of this class scope. – abatishchev Feb 10 '13 at 08:17
  • @DavidTorrey: However you can separate class holding a reference to the instance, and class instance of which you're actually referencing. But what for? Separation of concerns? May be. – abatishchev Feb 10 '13 at 08:17