delegate return

In this chapter you will learn:

  1. Define return type for delegate
  2. return int from delegate

delegate return type

The return type of a delegate can be more specific than the return type in delegate declaration.

For example, the delegate specifies that the return type is object, it may return a string type value.

using System;// ja v  a2 s  .c om

delegate object Create();


class Test
{

    static string createString()
    {
        return "java2s.com";
    }

    static void Main()
    {
        Create c = createString;

        c();
    }
}

return int from delegate

using System;//from   ja va2  s.  c  o  m

delegate int FunctionToCall();

class MainClass
{
   static int IntValue = 5;

   public static int Add2() {
       IntValue += 2;
       return IntValue;
   }

   public static int Add3() {
      IntValue += 3;
      return IntValue;
   }

   static void Main()
   {
      FunctionToCall functionDelegate = Add2;
      functionDelegate += Add3;
      functionDelegate += Add2;

      Console.WriteLine("Value: {0}", functionDelegate());
   }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. How to use Func and Action from system namespace
Home » C# Tutorial » delegate, lambda, event
delegate
Multicast delegate
delegate variables
delegate parameters
Generic delegate
delegate return
Func and Action
delegate new
chained delegate
Anonymous delegate
delegate array
Return a delegate
delegate as parameter
Event
event multicast
static event
EventHandler
Event pattern
lambda
lambda syntax
Func, Action and lambda
lambda with outer function
lambda iteration variables