Search code examples
c#anonymous-methodsanonymous-class

C# How to do this anonymous method injection


How do I use something like this in C#.

 Console.WriteLine("yaya instant");
 Server.registerEvent(new Event(5000) {
    public void doWork() {
        this.stop();
        Console.WriteLine("yaya 5 seconds later");
    }
  });

Event class and the doWork() method is declared inside Event class.

Pretty much what is going on is doWork() is abstract method which should get created by the code above.

Whats the proper syntax to do this in C#? is it even possible to do anonymous methods like this?. (The above code is not valid syntax, if someone doesn't understand this question.)

Thank you I appreciate the help.


Solution

  • No you can't do this. You need to create a sub class of Event that accepts an action.

    public class MyEvent: Event
    {
        private Action _action;        
    
        public MyEvent(int milliseconds, Action action)
            : base(milliseconds)
        {
            _action= action;
        }
    
        public override void doWork()
        {
            action()
        }
    }
    

    Then you can do this:

    Server.registerEvent(new MyEvent(5000, () => 
        {
            this.stop();
            Console.WriteLine("yaya 5 seconds later");
        }));
    

    You just need to declare MyEvent once (call it something better), and then you can create instances of it with different actions when you need them.