How To Create Callbacks in C#

How To Create Callbacks in C#

2 Comments on How To Create Callbacks in C#

Introduction
Information can be sent from a class to a parent class. This can be done by setting up delegates. The delegate will describe the function and a parameter will let the parent class connect to it.

Example
To send a string value and receive a boolean value:

public delegate bool MyCallback(string Text);
public MyCallback OnCallBack { get; set; }

It is best to test if the parent class has connected to the delegate first before calling it by checking if the parameter is null:

bool rval = false;
if (OnCallBack != null) rval = OnCallBack("Hello World!");
if (rval == true)
    Console.WriteLine("Returned True");
else
    Console.WriteLine("Returned False");

In the above example, a default value was given to rval and OnCallBack is only called if the parent class connected to it. The result is then outputted to the console.

The parent class can receive the callback functions by connecting. This can be done when the class is initializing:

myclass.OnCallBack += CallBackFunction;

The last thing that is needed is a function that matches the callback delegate. The function needs to be created in the parent class with the same name that was used while connecting:

public bool CallBackFunction(string Text)
{
    return true;
}

In the above example, the function does nothing but return a true value to show the function was called.

About the author:

Bill Payne started working as a paid professional software developer at the young age of 12 years old developing simple games and other applications for pre-packaged computers. Bill has since developed software for many industries such as direct sales and the the stock market. Bill has now started sharing his many years of software development experience through a blog on the MPSHouse website and one on one lessons.

2 Comments

  1. Confused  - 12 April , 2014 - 11:21 pm
    Reply /

    Confusing as it gets.
    In “public MyCallback OnCallBack { get; set; }” what on Earth is this get and set coming from? Why are they there? Never used. What does this actually do?

    “The parent class can receive the callback functions…”
    I haven’t seen any inheritance here.

    “myclass.OnCallBack += CallBackFunction;”
    Where is “myClass” coming from?
    And how does “OnCallBack ” ‘store’ the pointer to the function to be called?

    Recaptcha IS IDIOTIC!

    • bill  - 13 April , 2014 - 10:08 am
      Reply /

      You just answered your own question in your comment. You said “OnCallBack” is never used then ask where “myclass.OnCallBack” is coming from. The get; set; stores the callback function. I do not know what you mean by “coming from”?

      Recaptcha has stopped 95% of my comment spam.

Leave a comment

Back to Top