0

First of all, I'm sorry if it's a duplicate. I don't know the right words to describe my problem.

Is it possible to change the method of an object to another method in another class like this?

public Class Controller
{
    void DoAction()
    { // Do something here }
}

public Class TheCaller
{
    Controller c = new Controller();
    TheCaller()
    {
        c.DoAction = AnotherAction; // Replace it with another method
    }
    void AnotherAction()
    { // Do something else here }
}

The closest I get was using Delegate, but Delegate only accept static functions.

Can someone help?

Nicolas Dias
  • 641
  • 11
  • 22
  • 1
    No, you can't remap `DoAction` unless it was designed to do that at the `Controller` class level. If you have control over the `Controller` class, you could make `DoAction` an `System.Action` (delegate) which can remap it for a specific instance. I'm not sure where you got that a delegate can only accept `static` functions, that isn't the case. – Ron Beyer Nov 24 '15 at 13:00
  • @RonBeyer Thank you! I never realize that `System.Action` would actually do the trick! Also for the delegate on `static` functions, I tried it like this: `public delegate void DoAction();` but when I tried to assign it to another method it said that it needs to be `static` -- or maybe I mistranslated it... Again, thank you! –  Nov 24 '15 at 13:16
  • Thats because when you define a delegate like that it only defines the signature for the delegate, it doesn't create an instance of it. If you wanted to have that work, you would have to create a member in your class, like `public DoAction DoActionMethod { get; set; }` which would be an instance of the delegate. – Ron Beyer Nov 24 '15 at 13:36

0 Answers0