0

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?

2
Contributors
2
Replies
4
Views
7 Years
Discussion Span
Last Post by EricTetz
1

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.

0

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.

Edited by EricTetz: To add information

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.