How to call a method without knowing it's name in C#? -
this question has answer here:
is possible call method without knowing it's name? imagine being method stored variable so:
public static method example; private static void dosomething() { //something } private static void main() { example = dosomething(); } public static void executesomething() { example(); }
is there this, or of similar function? i've looked @ delegates , i'm not sure if understand them correctly, or if it's i'm looking for.
what describing called delegate
. can used in variable/field/property/eventhandler declarations. c# comes handy generics can use describe function expect. examples:
action // void function action<t> // void function accepts parameter of type t action<tin1, tin2, ...> // void function accepts tx parameters func<t> // function returns object of type t func<tout, tin1, tin2, ...> // function returns tout accepts tx parameters predicate<t> // function returns bool , accepts parameter t
or if want write own delegates delegate
keyword:
delegate void myspecialeventhandler(object sender, object data)
example:
//eventhandler definition public delegate void printedsomethingeventhandler(string message); //event public event printedsomethingeventhandler printedsomething; //e.g. "function hook" private func<string,string> _externalfilter; public void setfilter(func<string,string> filter) { _externalfilter = filter; } private void printa(string message) { debug.writeline(message); } private void printb(string message) { console.writeline(message); } private bool containsprofanity(string message) { return message.contains("%$&!"); } public void print(string message, bool debug) { action<string> action; predicate<string> filter = containsprofanity; if(filter(message)) return; if(_externalfilter != null) message = _externalfilter(message); if(debug) action = printa; else action = printb; action(message); if(printedsomethingeventhandler != null) printedsomethingeventhandler(message); }