Reputation: 140
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
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:
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.In other words. An interface is more flexible than a delegate.
Upvotes: 8