In some class method, A, I need to call a library method B, which takes as an IProgress<Object> as a parameter.
Normally, I might either implement IProgress<Object> as part of class where A resides, and then pass “this” to method B. Or perhaps I might create a new class whose only purpose is to implement IProgress<Object> and handle it correctly– then in this case I’d create an instance of that class and pass it to B.
But what I really want is to have my implementation of IProgress<Object> to appear right inside the method in which I’m calling B, so that there’s less of a visual disconnect between the calling code, and the IProgress<Object> implementation. (I consider my implementation of IProgress to be kind of a private, non-shared detail of the calling method and thus I don’t want my implementation of IProgress<Object> to be in a whole separate method of perhaps a whole other class).
What I’ve been trying to do is use a lambda in which I will define my short progress handling, and then somehow pass this lambda to B, like this:
method in class A {
...
Action<Object> Report = (m) => { // do something useful with m };
B(Report)
}
method B(IProgress<Object> reporter) {
reporter.Report(some object)
}
Of course, I know why this won’t work as is – B is wanting an object that implements IProgress<Object> and I’m handing it an Action object instead.
Is there any way to achieve what I’m trying to achieve? (IE have my implementation if IProgress<Object> appear inside method A?
Delegates cannot implement interfaces (directly).
Two good options come to mind:
Change the definition of the method that you’re calling to take a delegate types instead of an
IProgresstype. (If possible; this would be the preferable option)Create a new type that implements the interface that you need and takes a delegate as a parameter to implement that functionality.
And example of #2, while dependent on the interface, might look something like this:
then you’d be able to do something like: