title: Mono.Cecil: create local variable and change return statement
body: <p>I'm trying to rewrite the get method of an property from:</p>
  
  <pre><code> get
   {
      return dataString;
   }
  </code></pre>
  
  <p>to:</p>
  
  <pre><code> get
   {
      string temp = dataString;
      PropertyLogging.Get("DataString", ref temp);
      return temp;
   }
  </code></pre>
  
  <p>So far I've tried differnt things:</p>
  
  <pre><code>//the static method I#m trying to insert
  var getMethod = att.AttributeType.Resolve().Methods.FirstOrDefault(x =&gt; x.Name == _getMethodName);
  if (getMethod != null)
  {
      // ilProcessor.InsertBefore(returnInstruction, ilProcessor.Create(OpCodes.Starg, 1));
  
      ilProcessor.InsertBefore(returnInstruction, ilProcessor.CreateLoadInstruction(property.Name));
  
      // ilProcessor.InsertBefore(returnInstruction, ilProcessor.Create(OpCodes.Ldloc, 0));
      ilProcessor.InsertBefore(returnInstruction, ilProcessor.Create(OpCodes.Ldloca_S,  0));
  
      ilProcessor.InsertBefore(returnInstruction, ilProcessor.Create(OpCodes.Call, currentMethod.Module.ImportReference(getMethod)));
  
  }
  </code></pre>
  
  <p>But it always ends in code like (decompiled with ilspy):</p>
  
  <pre><code>get
  {
      string text = this.dataString;
      string arg_17_0 = text;
      string text2;
      PropertyLogging.Get("DataString", ref text2);
      return arg_17_0;
  }
  </code></pre>
  
  <p>The IL code i currently have is:</p>
  
  <pre><code>IL_0000:  nop         
  IL_0001:  ldarg.0     
  IL_0002:  ldfld       UserQuery.dataString
  IL_0007:  stloc.0     // text
  IL_0008:  ldloc.0     // text
  IL_0009:  stloc.1     // arg_17_0
  IL_000A:  ldnull      
  IL_000B:  stloc.2     // text2
  IL_000C:  ldstr       "DataString"
  IL_0011:  ldloca.s    02 // text2
  IL_0013:  call        UserQuery+PropertyLogging.Get
  IL_0018:  nop         
  IL_0019:  ldloc.1     // arg_17_0
  IL_001A:  stloc.3     
  IL_001B:  br.s        IL_001D
  IL_001D:  ldloc.3     
  IL_001E:  ret    
  </code></pre>
  
  <p>But what I need is:</p>
  
  <pre><code>IL_0000:  nop         
  IL_0001:  ldarg.0     
  IL_0002:  ldfld       UserQuery.dataString
  IL_0007:  stloc.0     // temp
  IL_0008:  ldstr       "DataString"
  IL_000D:  ldloca.s    00 // temp
  IL_000F:  call        UserQuery+PropertyLogging.Get
  IL_0014:  nop         
  IL_0015:  ldloc.0     // temp
  IL_0016:  stloc.1     
  IL_0017:  br.s        IL_0019
  IL_0019:  ldloc.1     
  IL_001A:  ret 
  </code></pre>
  
  <p>I've also tried ti create a new variable in the method body, but I don't have a clue how to use it.</p>
  
  <p>Does anyone know how to correctly rewrite this get method?</p>
  
  <p>thanks in advance</p>