Quick Start
This tutorial takes you from an empty console project to a program that hooks a method, calls the original, removes the hook, edits a method's IL at runtime, and orders two hooks from different "mods". Every step shows the expected output. The behavior shown is derived from MonoMod's source and unit tests (HookTest, ILHookTest, DetourOrderTest).
1. Create a Project
dotnet new console -n HookDemo
cd HookDemo
dotnet add package MonoMod.RuntimeDetour
2. Write the Code You Will Hook
Replace Program.cs with a small "game" class. The methods are marked NoInlining: a method the JIT inlines into its caller is copied into that caller, and a detour on the original never sees those calls.
using System;
using System.Runtime.CompilerServices;
public class Player
{
public int Health = 100;
[MethodImpl(MethodImplOptions.NoInlining)]
public int TakeDamage(int amount)
{
Health -= amount;
return Health;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static string Greet(string name) => "Hello, " + name;
}
3. Add a Hook That Calls the Original
A Hook redirects a source method to a target. If the target's first parameter is a delegate matching the source's signature, MonoMod passes in a delegate (by convention named orig) that runs the rest of the chain and finally the original method. For an instance method, the this object becomes an explicit first parameter after orig.
using System;
using System.Reflection;
using MonoMod.RuntimeDetour;
public static class Program
{
public static void Main()
{
MethodInfo takeDamage = typeof(Player).GetMethod(nameof(Player.TakeDamage))!;
var hook = new Hook(takeDamage,
(Func<Player, int, int> orig, Player self, int amount) =>
{
Console.WriteLine($"[hook] halving {amount} damage");
return orig(self, amount / 2);
});
var p = new Player();
Console.WriteLine(p.TakeDamage(40));
hook.Dispose(); // undo the hook
Console.WriteLine(p.TakeDamage(40));
}
}
Run it:
dotnet run
Expected output:
[hook] halving 40 damage
80
40
The first call went through the hook (100 − 20 = 80); the second ran the original method directly (80 − 40 = 40).
The hook is applied as soon as the constructor returns (pass applyByDefault: false to delay it, then call Apply()). Disposing it, or letting the garbage collector collect it, undoes it. Keep a reference to every hook you want to stay active; see Hook lifetime.
4. Replace a Static Method Without Calling the Original
If the target has exactly the source's parameters (no leading delegate), the original is simply not reachable from the hook:
MethodInfo greet = typeof(Player).GetMethod(nameof(Player.Greet))!;
using (new Hook(greet, new Func<string, string>(name => "Hi " + name + "!")))
{
Console.WriteLine(Player.Greet("Ana"));
}
Console.WriteLine(Player.Greet("Ana"));
Expected output:
Hi Ana!
Hello, Ana
5. Change a Method's IL With ILHook
An ILHook gives you an ILContext for a copy of the method body, which you edit with an ILCursor. Here the cursor finds the ldarg.1 that loads amount and inserts code right after it to double the value:
using Mono.Cecil.Cil;
using MonoMod.Cil;
using (new ILHook(takeDamage, il =>
{
var c = new ILCursor(il);
c.GotoNext(MoveType.After, i => i.MatchLdarg(1)); // after "load amount"
c.EmitLdcI4(2); // push 2
c.Emit(OpCodes.Mul); // amount * 2
}))
{
Console.WriteLine(new Player().TakeDamage(10));
}
Expected output:
80
If no instruction matches, GotoNext throws KeyNotFoundException; use TryGotoNext to handle that case yourself. If your edit produces invalid IL, the ILHook constructor throws (for example InvalidProgramException) and the method keeps working unmodified. See ILHook.
6. Make Two Mods Cooperate
When several hooks target the same method, give each a DetourConfig with an ID. before/after lists reference other IDs:
MethodInfo greet = typeof(Player).GetMethod(nameof(Player.Greet))!;
using var a = new Hook(greet,
(Func<string, string> orig, string n) => "[A " + orig(n) + "]",
new DetourConfig("ModA"));
using var b = new Hook(greet,
(Func<string, string> orig, string n) => "[B " + orig(n) + "]",
new DetourConfig("ModB", before: new[] { "ModA" }));
Console.WriteLine(Player.Greet("Ana"));
Expected output:
[B [A Hello, Ana]]
ModB runs first (it is the outermost wrapper) because it asked to run before ModA, even though it was applied later. The full rules are on Detour Order.
7. See What MonoMod Is Doing
MonoMod logs through its own DebugLog. Set an environment variable before starting the process to write the log to standard output:
MONOMOD_LogToFile=- dotnet run
Lines look like [MonoMod.RuntimeDetour](<local time>) Trace: Creating Hook from ... to .... See Switches and Logging.
Next Steps
- Hook: all constructor overloads and signature rules.
- ILHook and ILCursor: searching and editing IL.
- Detour Order: priorities, contexts, and the ordering algorithm.
- HookGen:
On.Type.Method += ...events instead of reflection. - Troubleshooting