Search code examples
.netgenericsdelegatestemplate-method-pattern

Templated delegates


I have the following piece of code pattern:

void M1(string s, string v)
{
  try
  {
    // Do some work
  }
  catch(Exception ex)
  {
    // Encapsulate and rethrow exception
  }
}

The only difference is that the return type and the number and types of parameters to the methods can vary.

I want to create a generic / templated method that handles all of the code except for the "Do some work" part, how can it be achieved.


Solution

  • I like the Action

    public static void Method(Action func)
    {
        try
        {
            func();
        }
        catch (Exception ex)
        {
            // Encapsulate and rethrow exception
            throw;
        }
    }
    
    
    
    public static void testCall()
    {
        string hello = "Hello World";
    
        // Or any delgate
        Method(() => Console.WriteLine(hello));
    
        // Or 
        Method(() => AnotherTestMethod("Hello", "World"));
    
    }
    
    public static void AnotherTestMethod(string item1, string item2)
    {
        Console.WriteLine("Item1 = " + item1);
        Console.WriteLine("Item2 = " + item2);
    }