Methods that return delegates with .net2

184 Views Asked by At

I've been working in .net 4 and really enjoying the ability to return bespoke functions from a single method e.g:

public Func<object, object> FunctionBuilder(object o) 
{ /*build functions, woo*/ }

...however this appears very difficult if not impossible to do within .net2 since Func appears in .net3.5(?) and something like:

public delegate<object> FunctionBuilder(object o) 
{ /*nope*/ }

...is not valid syntax..

Is it even possible to return bespoke functions from a method within .net2?

2

There are 2 best solutions below

0
On BEST ANSWER

Is it even possible to return bespoke functions from a method within .net2?

Absolutely, but you need to return a specific delegate type.

The simplest thing is probably to declare your own generic delegates, e.g.

public delegate TResult ProjectFunc<T, TResult>(T arg)

And then:

public ProjectFunc<object, object> FunctionBuilder(object o)

Then if/when your project moves to .NET 3.5, you can just remove ProjectFunc and use Func instead. We've taken this exact approach in Noda Time (which actually now uses .NET 3.5 anyway) and it's worked fine.

0
On

You should use this construct.

delegate object MyDelegate(object);

MyDelegate FunctionBuilder()
{

}