0

Is there a way to redefine a function definition/method in C#?

Situation:

Modding someone else's code, and they have:

namespace TheirCode 
{
  public static class SomeUtility
  {
    public static void A(this Thing thing) 
    {
      //do something I want to change
    }
  }
}

I can load another dll that will allow me to insert my own code...but I want to change the behavior of a_thing.A(); I need the changes to affect all Things, not just any derived NewThings I might create.

Can I rewrite the method definition somehow? Can I change the behavior another way?

Thanks

Peter Kay
  • 133
  • 7
  • You're not clear about whether `A()` is static or not. It matters a little. And is their assembly signed? Open source? – H H Jul 29 '18 at 19:27
  • Short answer: No. Not without decompiling and recompiling. – H H Jul 29 '18 at 19:29
  • Here recompiling would involve replacing the author's .dll with my own .dll, instead of just creating my own additional .dll to be loaded? – Peter Kay Jul 29 '18 at 19:32
  • Yes. And when it's signed you better have control over all dependent pieces. – H H Jul 29 '18 at 19:34
  • Loks to be possible, but looks noz to be simple at all: https://www.codeproject.com/Articles/37549/CLR-Injection-Runtime-Method-Replacer – ZorgoZ Jul 29 '18 at 20:27
  • Look in to the terminology "code weaving" and the library `Mono.Cecil`, that may help you get started. – Scott Chamberlain Jul 29 '18 at 20:46

1 Answers1

0

Oh wow, there's a whole series of answers in this other question:

Dynamically replace the contents of a C# method?

The Harmony answer looks great!

I don't know why I couldn't find it earlier when I was searching; maybe this question's search terms will help someone else.

Peter Kay
  • 133
  • 7