Call Delegate methods from another class
c#, objective-c
Solution
A delegate is an object that points to a method, be it a static or instance method. So for your example, you would just use the event model:
class Caller {
public void Call() {
new Callee().DoSomething(this.Callback); // Pass in a delegate of this instance
}
public void Callback() {
Console.WriteLine("Callback called!");
}
}
class Callee {
public void DoSomething(Action callback) {
// Do stuff
callback(); // Call the callback
}
}
...
new Caller().Call(); // Callback called!
The `Caller` instance passes a delegate to the `Callee` instance's `DoSomething` method, which in turn calls the pointed-to method, which is the `Callback` method of the `Caller` instance.
Problem
I am having trouble figuring out how to program delegate method calls across classes in C#. I am coming from the world of Objective-C, which may be confusing me. In Objective-C, I can assign a delegate object inside a child class, to be the parent class (I.e., `childViewcontroller.delegate = self;`). Then I can to fire a method in the delegate class by using: ``` if([delegate respondsToSelector:@selector(methodName:)]) { [delegate methodName:parametersgohere]; } ``` However, I can't figure out how to do this in C#. I've read a bit about C# delegates in general (for example, here), but I'm still stuck. Are there any examples that explain this? Here is my scenario in full: I have classA which instantiates an instance of classB. ClassB fires a method (which call a web service), and upon response, I'd like to fire a method in classA. Any 'Hello World' types of tutorials out there that might explain the very basics of this?