title: Override Method Group On-The-Fly
body: <p>I have a base class that implements an interface:</p>
  
  <pre><code>internal interface ITest
  {
      virtual void GetData();
  }
  
  internal class Test : ITest
  {
      public void GetData()
      {
          Console.WriteLine("Test - Hello World!");
      }
  }
  </code></pre>
  
  <p>It is used by inheriting the <strong>Test</strong> class and overriding the <strong>GetData()</strong> method:</p>
  
  <pre><code>internal class SubTest : Test
  {
      public override void GetData()
      {
          Console.WriteLine("SubTest - Hello World!");
      }
  }
  </code></pre>
  
  <p>I have hundreds of stored procedures that each need to be called 1 time. Creating a new class like <strong>SubTest</strong> for each stored procedure that inherits from <strong>Test</strong> seems like overkill.</p>
  
  <p>Is there a way to write a Lambda Expression, Anonymous Method, or Action that will let me override the empty default method?</p>
  
  <p>What I'm thinking is something along these lines:</p>
  
  <pre><code>var t = new Test();
  t.GetData = delegate()
  {
      Console.WriteLine("Anonymous - Hello World!");
  };
  </code></pre>
  
  <p>Is there any way to write an override for a method <em>on-the-fly</em> like that?</p>
  
  <h2>Solved!</h2>
  
  <p>I used Evk's technique to apply what Gusman showed:</p>
  
  <pre><code>internal interface ITest
  {
      virtual void GetData();
  }
  
  internal class Test : ITest
  {
      public void GetData()
      {
          Console.WriteLine("Call from Test");
      }
  }
  
  internal class SubTest : Test
  {
      private readonly Action _localTest;
      public SubTest(Action localTest)
      {
          _localTest = localTest;
      }
      public override void GetData()
      {
          base.GetData();
          _localTest();
      }
  }
  </code></pre>
  
  <p>Here is how I implemented it:</p>
  
  <pre><code>class ClassTester
  {
      public void Run()
      {
          var t = new Test(() =&gt;
              {
                  Console.WriteLine("Anonymous Override of Test");
              }
          );
          t.GetData();
      }
  }
  </code></pre>