Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert method to Delegate?

I want to call for example TryDo.Do(MessageBox.Show(""), null);

how can I do that??

using System;

namespace TryCatchHandlers
{
    public static class TryDo
    {
        public static CallResult Do(Delegate action, params object[] args)
        {
            try
            {
                return new CallResult (action.DynamicInvoke(args), action.Method.ReturnType, true);
            }
            catch
            {
                return new CallResult(null, null, false);
            }
        }
    }

    public class CallResult
    {
        public CallResult() { }

        internal CallResult(object result, Type resultType, bool isSuccessful)
        {
            Result = result;
            ResultType = resultType;
            IsSuccessful = isSuccessful;
        }
        public object Result { get; private set; }
        public Type ResultType { get; private set; }
        public bool IsSuccessful { get; private set; }
    }
}

2 Answers

Your code calls MessageBox.Show, then tries to pass the result to TryDo.
Since MessageBox.Show doesn't return a Delegate, that won't work.

Instead, you should pass the Show method itself, along with a parameter:

TryDo.Do(new Func<string, DialogResult>(MessageBox.Show), "");

Alternatively, you can pass an anonymous method that calls the function:

TryDo.Do(new Action(() => MessageBox.Show("")));

Note that your function will perform faster if you make generic overloads that take Funcs and Actions instead of taking a Delegate and calling DynamicInvoke.

like image 129
SLaks Avatar answered Aug 15 '26 12:08

SLaks


Try this:

Delegate d = (Action)delegate { MessageBox.Show(""); };
TryDo.Do(d, null);
like image 23
ConsultUtah Avatar answered Aug 15 '26 10:08

ConsultUtah