aWrongun
aWrongun

Reputation: 276

Method to return a generic type when passing in a delegate as a parameter

I'm trying to 'genericize' some code we have spattered around our system.

I want to:

  1. return a generic type,
  2. pass in some kind of delegate containing the method to be called.

I'm pretty new to generics so any help appreciated.

Below is where my finger in the air is(!)

public static T ReturnSingleObject<T>(Func<string, int, T> dynamicSignature)
    {
        T returnValue;
        ServiceReference wCFService;
        try
        {
            wCFService = new BusinessServiceClient();

            returnValue = dynamicSignature();

            //returnValue = wCFService.AMETHOD(PARAM1, PARAM2);
            return returnValue;
        }
        catch (Exception)
        {
            if (wCFService != null) wCFService.Abort();
            throw;
        }
        finally
        {
            if (wCFService != null) wCFService.Close();
        }
    }

Upvotes: 0

Views: 1533

Answers (1)

Mark Synowiec
Mark Synowiec

Reputation: 5445

It looks like you're missing a couple parameters for your dynamicSignature function, so you'll need to add those. Also, you might move your return statement to the bottom, out of the try block, and initialize your return value to the default value:

T returnValue = default(T);
...
try
{
   ...
   returnValue = dynamicSignature(somestring, someint);
   ...
}
...

return returnValue;

Upvotes: 2

Related Questions