Asat0r
Asat0r

Reputation: 65

c# change modifier when creating event method with +=

If I subscribe a new Method to a Handler and Press "Tab" twice after the "+=" VS will implement a Body like:

public class A {
  public A(){
    button1.Click += OnButton1Click();
  }

  private OnButton1Click(object sender, EventArgs e){

  }
}

How can I change VS to create the Body of the Method as public instead of private?

Kind regards, Asat0r

Upvotes: 0

Views: 167

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1503290

Other answers have suggested that the method shouldn't be public.

Broadly speaking, I reject that - at least without further justification. If you want to expose a method with exactly that signature, I'd normally go ahead and do so. Two caveats around that though:

  • Normally the signature of an event handler isn't useful except as an event handler; the parameters aren't generally useful when calling the method directly. There are exceptions to that as ever.
  • If you subscribe an event handler with a public method, any other code can unsubscribe that event handler by creating an equal delegate. If you control all the code in the application, that's not much of a problem.

Both cases can be solved by exposing a public method with exactly the parameters you want (which could still be event handler parameters, but often won't be) and then using a lambda expression to subscribe to the event:

// I want to be able to call this from other code
public void SaveItem()
{
    // ...
}

// Hook up the event handler using a lambda expression
saveButton.Click += (sender, args) => SaveItem();

On the other hand, if neither of the bullet points are an issue, go ahead and make the method public manually. I wouldn't expect there to be a VS shortcut to do so, but simply specifying the public modifier is pretty simple.

Upvotes: 1

Rahul
Rahul

Reputation: 77926

How can I change VS to create the Body of the Method as public instead of private?

Not sure if there is any option but why you would like to do that? event handlers are not meant to be public. If you want to call the logic inside handler from some other type then refactor that logic to a helper method and re-use that instead probably.

Upvotes: 1

Related Questions