title: Is there a way to automatically add wrapper code to all public functions of a class?
body: <p>I have a C# class. (Note that this is just to illustrate the problem. The real-world code is more complex than this.)</p>
  
  <pre><code>class MyClass
  {
      private readonly MyCustomData myData = new MyCustomData();
      private int flarnCount = 0;
      /* Redacted more data structures. */
  
      public string One                             =&gt; myData[1];
      public List&lt;string&gt; Evens                     =&gt; myData.Where(item =&gt; item.Key % 2 == 0).Select(item =&gt; item.Value).ToList();
      public void SetValue(int index, string value) =&gt; myData[index] = value;
      public void Flarn()                            { flarnCount+=1; myData[flarnCount] += 12; }
  
      /* Redacted several hundred other similar functions. */
  }
  </code></pre>
  
  <p>It works great, except I want to be able to call it from multiple threads. No problem, I just add a line...</p>
  
  <pre><code>private readonly object mon = new object();
  </code></pre>
  
  <p>.. and add a lock(mon) command to each public function.</p>
  
  <p>And this is the problem. I <em>could</em> copy-and-paste that lock command into each of the several hundred public functions, but that seems like hard work and the end result would look really ugly.</p>
  
  <p>Is there a way I can tell the compiler to include the same wrapper inside all public functions?</p>
  
  <p>UPDATE - I could have equally asked how to add the same try/catch block to all public functions. Please don't get hung up on the locking problem itself which is just there to illustrate the problem.</p>