Implement protocol delegates

I would like to implement protocol and delegates as in Objective C for call back mechanism and delegation.

is it possible here ? and how to do that ?

Best Answer

  • TedRogersTedRogers US ✭✭✭✭
    edited March 2017 Accepted Answer

    Sure...
    1. Define an interface (Protocol)
    2. Add that interface to the object you want to call back into
    3. Pass that interface into the object that you want to call back from (either pass in constructor or create property)
    4. Store that interface object either as WeakReference or strong depending on your circumstance. (i.e. - if nobody holds onto the object it can be GC'd on you) (Delegate)

    I do this all the time when I create an object that implements UITableViewSource.

    Another nice way to do this is with event handlers.

Answers

  • TedRogersTedRogers USMember ✭✭✭✭
    edited March 2017 Accepted Answer

    Sure...
    1. Define an interface (Protocol)
    2. Add that interface to the object you want to call back into
    3. Pass that interface into the object that you want to call back from (either pass in constructor or create property)
    4. Store that interface object either as WeakReference or strong depending on your circumstance. (i.e. - if nobody holds onto the object it can be GC'd on you) (Delegate)

    I do this all the time when I create an object that implements UITableViewSource.

    Another nice way to do this is with event handlers.

  • Thanks,Its done the same way its done in Objective C ...If you have some sample code you can share as well

  • DaveHuntDaveHunt USMember ✭✭✭✭✭

    This is basic C# stuff and not specific to Xamarin. You can find a lot of good info on C# Corner. For example: Callback Operation By Delegate or Interface.

  • TedRogersTedRogers USMember ✭✭✭✭

    Also, take care when you use this pattern to make sure your objects are getting Disposed. Objects that are backed by iOS objects (UIViewController, etc.) can give the the same type of retain cycles you get with obj-c or Swift. That is why you sometimes need to use WeakReference.

  • I also need example of Objective C protocol example code, and correct connection to C# delegate. I can't find any example with both sides, and the binding in between.

Sign In or Register to comment.