Is is possible to define a method which returns a delegate, without first creating a delegate type?

For instance, in C or C++ I can define a function pointer type, then define a function which returns a function pointer of that type:

typedef int (*IntVoid)(); // function pointer type

IntVoid Foo() // function which returns function pointer
{
   // return pointer to function here
}

Similarly in C#, I can declare a delegate type, then declare a method which returns a delegate of that type:

delegate int IntVoid(); // delegate type

IntVoid Foo() // function which returns delegate
{
   // return delegate here
}

However, in C the typedef is not necessary, the declaration syntax is rich enough that I can define a 'function returning pointer to function which receives no parameters and returns int', like this:

int (*Foo())() // function which returns function pointer
{
   //  return pointer to function here
}

Can I do the same in C#? Is there some way to define a method which returns a delegate with a given signature, without first defining a delegate type?

Look at the generic Func<TResult> delegate system. You can do something like this

class Program
{
    static void Main(string[] args)
    {
        Func<int> function = GetFunction();
        Console.WriteLine(function());
        Console.Read();
    }

    static Func<int> GetFunction()
    {
        return () => Foo();
    }

    static int Foo()
    {
        return 1;
    } 
}

For more info, simply google "Func<T> C#" and follow the links to MSDN.

Ahh, that'll do! Thanks. :)

EDIT: Just discovered Action<T> which covers delegates with void return types. Still not quite as general as I'd hoped for, but those two should cover the majority of uses.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.