Using an anonymous delegate to return an object

Can I use an anonymous delegate to return an object?

Something like that:

object b = delegate { return a; };
+5
source share
3 answers

Yes, but only by calling it:

Func<object> func = delegate { return a; };
// or Func<object> func = () => a;
object b = func();

And, of course, the following is much simpler ...

object b = a;

The comments mention cross-thread exceptions; this can be fixed as follows:

If the delegate is what we want to run in the user interface thread from the BG stream:

object o = null;
MethodInvoker mi = delegate {
    o = someControl.Value; // runs on UI
};
someControl.Invoke(mi);
// now read o

Or vice versa (to run a delegate in BG):

object value = someControl.Value;
ThreadPool.QueueUserWorkItem(delegate {
    // can talk safely to "value", but not to someControl
});
+9
source

Just declare these static functions somewhere:

public delegate object AnonymousDelegate();

public static object GetDelegateResult(AnonymousDelegate function)
{
    return function.Invoke();
}

And use it everywhere you want:

object item = GetDelegateResult(delegate { return "TEST"; });

or even like that

object item = ((AnonymousDelegate)delegate { return "TEST"; }).Invoke();
+1
source
using System;

public delegate int ReturnedDelegate(string s);

class AnonymousDelegate
{
    static void Main()
    {
        ReturnedDelegate len = delegate(string s)
        {
            return s.Length;
        };
        Console.WriteLine(len("hello world"));
    }
}
0
source

All Articles