views:

108

answers:

3

I have numerous occurrences of the following in my code:

this.webBrowserCtrl.DocumentCompleted -= new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(this.LoginScreenLoaded);
this.webBrowserCtrl.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(this.AttemptLoginAnalysis);

I wish to remove this and use a simple method that takes 2 inputs - however I don't know what the types would be.

    private void DefineNewDocumentCompletedHandler(TYPEA inputA, TYPEB inputB)
    {

        this.webBrowserCtrl.DocumentCompleted -= new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(inputA);
        this.webBrowserCtrl.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(inputB);

    }

Does anyone know what TYPEA and TYPEB should be? Or another way to accomplish my goal?

+3  A: 

Use the delegate type on the input parameters, like this:

private void DefineNewDocumentCompletedHandler(WebBrowserDocumentCompletedEventHandler inputA, WebBrowserDocumentCompletedEventHandler inputB)
{
    this.webBrowserCtrl.DocumentCompleted -= inputA;
    this.webBrowserCtrl.DocumentCompleted += inputB;
}

Example of use:

DefineNewDocumentCompletedHandler(this.LoginScreenLoaded, this.AttemptLoginAnalysis);

The syntax new <delegate type>(<name of method>) is a C# 1.x construct that is now obsolete. From C# 2.0 onwards, you can just specify the name of the method without parentheses, and the compiler will automatically wrap it in a delegate instance for you.

Christian Hayter
@Christian - Thanks very much, especially for providing the actual code :-)
Jonno
+1  A: 

TYPEA and TYPEB are of WebBrowserDocumentCompletedEventArgs

this. __curious_geek
@this.__curious_geek - Thank you very much, if I could accept 2 answers I would accept yours too.
Jonno
@Jonno: Thanks, Christian's answer is better.
this. __curious_geek
+1  A: 

You can also make an extension method of the method described by Christian.

public static void DefineNewDocumentCompletedHandler(this WebBrowser webBrowser, WebBrowserDocumentCompletedEventHandler inputA, WebBrowserDocumentCompletedEventHandler inputB)
{
webBrowser.webBrowserCtrl.DocumentCompleted -= inputA;
webBrowser.webBrowserCtrl.DocumentCompleted += inputB;

}

and use it like

this.webBrowserCtrl.DefineNewDocumentCompletedHandler(this.LoginScreenLoaded, this.AttemptLoginAnalysis);
Tiju John
@Tiju - thats a pretty nifty idea, unfortunately I need to target .net 2.0 - but thanks for the idea!
Jonno