Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad form to use a generic callback?

I've got this code (well, something similar).

private delegate void GenericCallback<T>(T Info);

private void DoWork()
{
    System.Threading.Thread Worker = new System.Threading.Thread(
            delegate() 
            {
                TestMethod(TestMethodCallback<string>);
            }
    );
    Worker.Start();
}

private void TestMethod(GenericCallback<string> Callback)
{
    System.Threading.Thread.Sleep(1000);
    if(Callback != null)
    {
        Callback("Complete");
    }
}

private void TestMethod(GenericCallback<int> Callback)
{
    System.Threading.Thread.Sleep(1000);
    if(Callback != null)
    {
        Callback(25);
    }
}

private void TestMethodCallback<T>(T Info)
{
    MessageBox.Show(Info.ToString());
}

Which allows me to call different versions of TestMethod based on the type of a parameter, while also allowing me to have a single callback method.

Is this bad form, or an accepted practice?

like image 346
Tester101 Avatar asked Dec 09 '22 21:12

Tester101


2 Answers

It looks like you might be looking for the Action delegate type. It's basically what you have here: a generic void-returning delegate type.

like image 153
Thom Smith Avatar answered Dec 11 '22 11:12

Thom Smith


Such an established practice, that some of the work has been done for you. Action in this case, and Func should you return a value, are generic delegates, precisely like this. An advantage is, if I saw your signature:

private void TestMethod(GenericCallback<string> Callback)

I have to look up what GenericCallback<string> is. If I saw:

private void TestMethod(Action<string> callback)

I already know.

like image 20
Jon Hanna Avatar answered Dec 11 '22 11:12

Jon Hanna