knittl
knittl

Reputation: 265757

How to call delegate from string in C#?

Is it possible to call a delegate stored in a variable by its variable name (as a string)? I guess I'd have to use reflection mechanism, but I'm not getting anywhere

Example code:

class Demo {
  public delegate int DemoDelegate();

  private static int One() {
    return 1;
  }

  private static void CallDelegate(string name) {
    // somehow get the value of the variable with the name
    // stored in "name" and call the delegate using reflection
  }

  private static void CallDelegate(string name, DemoDelegate d) {
    d();
  }

  static void main(string[] args) {
    DemoDelegate one = Demo.One;
    CallDelegate(one);
    // this works, but I want to avoid writing the name of the variable/delegate twice:
    CallDelegate("one", one);
  }

}

Is this even possible? If so how?

Upvotes: 4

Views: 10045

Answers (5)

knittl
knittl

Reputation: 265757

I cannot remember what I wanted to achieve more than 10 years ago, but reading the question now, I want to present a potential workaround. The workaround doesn't completely avoid the duplication, but it gets rid of manually stringifying the name of the variable.

The nameof expression allows to produce the name of a variable, type, or member.

static void main(string[] args) {
  DemoDelegate one = Demo.One;
  CallDelegate(one);
  CallDelegate(nameof(one), one);
}

The identifier is still repeated, but at least now changing the name of the variable with a refactoring tool will change the name used for logging too. It is now impossible to forget to update the name used in logging, since that would result in a compilation error ("unknown identifier").

Upvotes: 0

Miguel Angelo
Miguel Angelo

Reputation: 24202

Yes, it is possible, as long as you use Linq Expressions, and little reflection.

Take a look at this code, it does something simillar to what I think you want:

using System;
using System.Linq.Expressions;
using System.Reflection;
using System.Collections.Generic;

namespace q6010555
{
    class Demo
    {
        static List<string> varNamesUsed = new List<string>();

        public delegate int DemoDelegate();

        private static int One()
        {
            return 1;
        }
        private static void CallDelegate(Expression<Func<DemoDelegate>> expr)
        {
            var lambda = expr as LambdaExpression;
            var body = lambda.Body;
            var field = body as MemberExpression;
            var name = field.Member.Name;
            var constant = field.Expression as ConstantExpression;
            var value = (DemoDelegate)((field.Member as FieldInfo).GetValue(constant.Value));

            // now you have the variable name... you may use it somehow!
            // You could log the variable name.
            varNamesUsed.Add(name);

            value();
        }
        static void Main(string[] args)
        {
            DemoDelegate one = Demo.One;
            CallDelegate(() => one);

            // show used variable names
            foreach (var item in varNamesUsed)
                Console.WriteLine(item);
            Console.ReadKey();
        }
    }
}

Upvotes: 2

peteisace
peteisace

Reputation: 2772

public void Fire(string name)
        {
            FieldInfo field = this.GetType().GetField(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

            if (field != null)
            {
                Delegate method = field.GetValue(this) as Delegate;

                if (method != null)
                {
                    method.Method.Invoke(method.Target, new object[0]);
                }
            }
        }

Obviously restricts you from having parameterized delegates.

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1063884

Variables barely exist. The only way to reliably call-by-string (in this scenario) would be to store the delegates in a dictionary:

Dictionary<string, DemoDelegate> calls = new Dictionary<string, DemoDelegate>
{
    {"one",one}, {"two",two}
}

Now store that dictionary somewhere (in a field, typically), and do something like:

private int CallDelegate(string name) {
    return calls[name].Invoke(); // <==== args there if needed
}

Upvotes: 7

thecoop
thecoop

Reputation: 46148

You can't really access variables in another stack frame (although I think it is possible using hackery around the StackFrame class). Instead, you'll be wanting to pass an Delegate object around and use methods like DynamicInvoke, if you want to invoke a generalised delegate in a reflection-like manner.

Upvotes: 0

Related Questions