Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify C# Class method during execution

Tags:

c#

oop

tdd

I'd like to override a class method without inheriting the base class because it'd take a lot of time and modifications and, therefore, more and more tests. It's like this:

class TestClass{
    public void initialMethod(){
        ...
    }
}

And somewhere on the code, I'd like to do something like this:

public testMethod()
{
    return;
}
test(){
    changeMethod(TestClass.initialMethod, testMethod);
}

And this changeMethod function would override the TestClass initialMethod so that it'd call testMethod instead.

Inheriting and overriding the method using normal practices is not an option, as this class A is a graphic component and, inhereting it (and changing it) would break lots of code.

Edit: We don't have the base code for the TestClass, so it's not an option to modify the code there defining the initialMethod as a delegate.

Edit 2: Since this is a graphical component, the designer added a lot of code automatically. If I were to inherit this code, I would have to replace all code added by the designer. That's why I wouldn't like to replace this component.

like image 879
Rodrigo Avatar asked Jan 21 '26 13:01

Rodrigo


1 Answers

You need the Strategy pattern.

Main steps:

  • Create an interface with ie. Do() signature
  • Your initialMethod() should call a strategy.Do(), where strategy is type of your interface
  • Create a class that implements this interface. Do() is your testmethod now.
  • Inject into your main class an instance of this class

If the job it's not so big (let's say just a color replacement or something) then I agree with Jhonny D. Cano's solution with C# (anonymous)delegates.

Edit (after edit 2)

May - just as proof-of-concept - you should inherit the class and replace all references from base class to this new. Do this, and nothing else. If it works, you can think about the next steps (new methods or delegates etc.)

You need only a new checkout from your version control system, and if it maybe fails you can abandon it. It's worth trying.

like image 83
boj Avatar answered Jan 24 '26 17:01

boj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!