Search code examples
c#.netcildynamic

Intercept call to property get method in C#


Let's assume that we have this class:

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Now, is it possible in C# to intercept call to property get method, run some other method and return result of that method instead of property value? I'd like to be able to do some additional logic behind the scene. The downside is that this class can't be changed (on C# level). Maybe some IL ?


Solution

  • The .NET SDK has what you need already. You can round-trip most anything on the CLR by disassembly/reassembly (ildasm.exe and ilasm.exe) if you are careful. Make sure to start a "Visual Studio Command Prompt" so these tools are in your PATH.

    1) ildasm person.exe

    2) File -> Dump (person.il)

    3) Edit and modify the get_Name() method: IMPORTANT: When modifying a method at the IL level, always recalculate .maxstack, since the Visual Studio .NET compilers will have set it exactly for most methods, if you add any code, raise .maxstack to handle the maximum # of values on the runtime stack for that method, if not you'll get an invalid program.

      .method public hidebysig specialname instance string get_Name() cil managed
      {
        .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) 
        // Code size       11 (0xb)
        .maxstack  2
        .locals init (string V_0)
        IL_0000:  ldarg.0
        IL_0001:  ldfld      string Person::'<Name>k__BackingField'
        IL_0006:  stloc.0
        IL_0009:  ldloc.0
            IL_000a:  ldstr "IL code inserted here"
            call    void [mscorlib]System.Console::WriteLine(string)
        IL_001a:  ret
     } // end of method Person::get_Name
    

    4) Re-assemble : ilasm person.il