0

I have some forms, and in them i have some event functions which are basically identical

I have tried to implement a 'Shared' class and link the Eventhandler to that function, but when i give the function the necessary protection level, it complains about it's non-static-ness and i have to make it static also.

I'm not a fan of static functions, and so ask: Is there a better way to do it?

(In case the above is unclear: I want to do this: Set up single event handler for multiple buttons in .NET? but with multiple forms instead of multiple controls)

EDIT: as per request for more info:

I'm fairly OCD about code duplication, and my program has multiple forms active/hidden at the same time, and obviously i want to close the whole program when the 'x' is pressed so:

class Shared
{
    public static void FormClosed(object sender, FormClosedEventArgs e)
    {
        Application.Exit();
    }

    public static void FormClosing(object sender, FormClosingEventArgs e)
    {
        if (MessageBox.Show("Are you sure you want to exit?", "Confirm exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) {
            e.Cancel = true;
        }
    }
}

Very simple functions, i know, but i don't like duplication :P

The above 'configuration' of 'public static' works fine, but i just wondered if there was a 'better way' (tm)

Community
  • 1
  • 1
LordAro
  • 1,269
  • 3
  • 18
  • 35
  • 1
    What objection do you have to static functions? –  Aug 23 '12 at 13:34
  • Can you share the code you have tried? There is nothing wrong with static event handlers and methods. I don't understand why the aversion to static methods ...??? – IAbstract Aug 23 '12 at 13:34
  • i guess it's a lack of understanding... :L I'm a relatively new programmer and have never understood the differences/why they are needed ... I'll go do that, shall i? :) – LordAro Aug 23 '12 at 13:37
  • 1
    We'd really need to know more about the function to know whether or not it should be static. There are lots of legitimate cases for it being either static or instanced, neither one is inherently better with the level of detail you've given. – Servy Aug 23 '12 at 13:53
  • There are several ways to do it - but static class and function seems the best. You can use a singleton class instead, or build it into your own form class (inherited from Form) with the code already in it so you only need do it once, intercept Windows Messages and react globally (this is horrible and avoided if possible - here be dragons!). You could also have the event in each form, and delegate internally as noirmal and just call a static function from within the call back code (just makes it indirect - but can allow for multiple eventargs etc easier - perhaps). – Wolf5370 Aug 23 '12 at 14:07
  • As to Designer - best not to. However, if you must, then add it above the generated code comment so it is just aprt of the partial class (things like ReSharper will move functions for you wiothin partial classes). – Wolf5370 Aug 23 '12 at 14:09
  • @LordAro Based on your update, the one thing I'd change is `class Shared` to `static class Shared`: it doesn't make sense for that class to have instance members, and with `static class Shared` that will be enforced. Other than that, I see no objection to having those as static methods. –  Aug 23 '12 at 14:09
  • ok, yeah, i'm 'sold' on the static function/class even if i don't fully understand what he difference between a static function and a non static function is :) Thanks for all your help – LordAro Aug 23 '12 at 14:11
  • @LordAro: are you changing the requirements for the answer to the original question? – IAbstract Aug 23 '12 at 14:17
  • i guess so, if you want to muscle in on the 'accepted answer' ;) – LordAro Aug 23 '12 at 15:04
  • @LordAro: changing the intent of the question will require edits to the original. In addition, changing intent will invalidate the answers already provided. – IAbstract Aug 23 '12 at 15:34
  • Well, what do you suggest i do? – LordAro Aug 23 '12 at 15:59

2 Answers2

1

If you don't want a static class, you have 2 easy options to suit most preferences:

  • singleton
  • pass parameter to form ctor

For a singleton:

class EventMangler {

   private static readonly _instance = new SomeHandler ();

   // although you don't like static methods  :(
   static EventMangler Instance {
      get { return _instance; }

   public void SomeEventHandler (object sender, EventArgs e) {
      // handle event
   }
}

// use EventMangler.Instance
public MyForm () {
   InitializeComponent();
   button1.Click += EventMangler.Instance.SomeEventHandler;
}

To pass a parameter to the Form's constructor, you have more choices: (a) pass reference to the handler's object, or (b) pass a reference to the handler itself. I prefer option (b) for a single handler. Otherwise, if the parent object - e.g. EventMangler - has multiple handlers, use option (a):

// remove singleton Instance method from EventMangler
// instantiate EventMangler in Program and pass to Form ctors

// pass a single handler reference as Action
public MyForm (Action<object, EventArgs> handler) {
   InitializeComponent();
   button1.Click += handler;
}
IAbstract
  • 19,551
  • 15
  • 98
  • 146
  • Furthermore, you could pass a singleton object with an EventHandler if the whole "action" thing is confusing. http://stackoverflow.com/a/85188/189475 – feathj Aug 23 '12 at 14:08
1

You can use static method and then delegate handling to instance and only then use all prettiness of OOP

public static void GeneralHandler(object sender, EventArgs args)
{
    instance.Handle(sender, args);
}
private static MyProcessingClass instance = new MyProcessingClass();

Subscribe like

button1.Event1 += GeneralHandler;
Button1.Event2 += GeneralHandler;
Button1.Event1 += GeneralHandler;

You can further enhance your implementation to support Dependency Injection, like introduce HandlerProvider and encapsulate creating mechanism there, while exposing only interface outside

Ilya Ivanov
  • 23,148
  • 4
  • 64
  • 90