tags:

views:

532

answers:

3

Does the term callback in the context of delegates mean ,"a delegate delegating it works to another delegate inorder to finish some task" ?

Example :(Based on my understanding,I have implemented a callback,correct me if it is wrong)

namespace Test
{
    public delegate string CallbackDemo(string str);


class Program
{
    static void Main(string[] args)
    {
        CallbackDemo handler = new CallbackDemo(StrAnother);
       string substr= Strfunc(handler);
        Console.WriteLine(substr);
        Console.ReadKey(true);
    }

    static string Strfunc(CallbackDemo callback)
    {
       return callback("Hello World");   
    }

    static string StrAnother(string str)
    {
        return str.Substring(1, 3).ToString();
    }
}

 }

Please provide examples as necessary.

+3  A: 

A callback is basically a delegate passed into a procedure which that procedure will "call back" at some appropriate point. For example, in asynchronous calls such as WebRequest.BeginGetResponse or a WCF BeginXxx operation, you'd pass an AsyncCallback. The worker will "call back" whatever method you pass in as the AsyncCallback, in this case when it's finished to let you know that it's finished and to obtain the result.

An event handler could be considered another example. For example, when you attach a handler to a Click event, the button will "call back" to that handler when the click occurs.

itowlson
+2  A: 

A callback is what the delegate executes when it is invoked. For example, when using the Asynchronous pattern using delegates, you would do something like this:

public static void Main(string[] args)
{
    Socket s = new Socket(...);

    byte[] buffer = new byte[10];
    s.BeginReceive(buffer, 0, 10, SocketFlags.None, new AsyncCallback(OnMessageReceived), buffer);

    Console.ReadKey();
}

public static void OnMessageReceived(IAsyncResult result)
{
    // ...
}

OnMessageReceived is the callback, the code that is executed by invoking the delegate. See this Wikipedia article for some more information, or Google some more examples.

nasufara
+2  A: 

Your example is a good start, but it is incorrect. You don't make a new delegate in the method, it's used in the declaration of an event in the class. See this modified example of your code:

namespace Test
{
    //In this case, this delegate declaration is like specifying a specific kind of function that must be used with events.
    public delegate string CallbackDemo(string str);
    class Program
    {
        public static event CallbackDemo OnFoobared;
        static void Main(string[] args)
        {
            //this means that StrAnother is "subscribing" to the event, in other words it gets called when the event is fired
            OnFoobared += StrAnother;
            string substr = Strfunc();
            Console.WriteLine(substr);
            Console.ReadKey(true);
            //this is the other use of delegates, in this case they are being used as an "anonymous function". 
            //This one takes no parameters and returns void, and it's equivalent to the function declaration 
            //'void myMethod() { Console.WriteLine("another use of a delegate"); }'
            Action myCode = delegate
            {
                Console.WriteLine("another use of a delegate");
            };
            myCode();
            Console.ReadKey(true);
            //the previous 4 lines are equivalent to the following however this is generally what you should use if you can
            //its called a lambda expression but it's basically a way to toss arbitrary code around
            //read more at http://www.developer.com/net/csharp/article.php/3598381/The-New-Lambda-Expressions-Feature-in-C-30.htm or 
            //http://stackoverflow.com/questions/167343/c-lambda-expression-why-should-i-use-this
            Action myCode2 = () => Console.WriteLine("a lambda expression");
            myCode2();
            Console.ReadKey(true);
        }

        static string Strfunc()
        {
            return OnFoobared("a use of a delegate (with an event)");
        }
        static string StrAnother(string str)
        {
            return str.Substring(1, 3).ToString();
        }
    }
}

I've only scratched the surface here; search stack overflow for "delegate c#" and "lambda expression c#" for lots more!

RCIX
Thank you very much
you're welcome!
RCIX