Bruce Thompson
Bruce Thompson

Reputation: 140

Implement call back in C#

New to C# and trying to figure out how to do a call back. (if this is indeed a callback)

I have a number of calls in the format ..

        connector.Subscribe(data1, data2, (element, value) =>
        {
            Log($"{element.Name}: {value}");
        });

and I would like to have them all use the same function instead of adding the code to each For example

    public void somefunction(element, value)
    {
        Log($"{element.Name}: {value}");
    }

    connector.Subscribe(data1, data2, somefunction);

Honestly, I have no idea where to start so any help is appreciated

Upvotes: 3

Views: 471

Answers (1)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112259

Declare a delegate with a signature matching the function's signature. E.g.:

public delegate void MyCallback(string name, int value);

Then declare Subscribe as

public void Subscribe(object data1, object data2, MyCallback myCallback)
{
}

Then you can do what you asked for:

connector.Subscribe(data1, data2, somefunction);

Note that somefunction must be written without the parameter braces here.


Another way to solve the problem is to declare an appropriate interface. E.g. an ILogger interface. Instead of passing a logger function, you would pass a logger object.

This has advantages:

  • You can inject a logger. See Dependency injection (Wikipedia).
  • You can configure the logger to be used in a central place by using an IoC Container (TutorialsTeacher).
  • You can create a wrapper object implementing ILogger that itself accepts a list of ILogger objects in a constructor. E.g. you could pass it a console logger and a file logger. The call sites don't need to know that you want everything to be logged twice.
  • You can use a dummy logger doing nothing if you don't want to log (again without changing the call sites).

In other words. An interface is more flexible than a delegate.

Upvotes: 8

Related Questions