How to use System.Action with return type?

19,781

Solution 1

You need to use Func to represent a method which will return a value.

Below is an example

    private List<int> GetData(string a, string b)
    {
        return TryAction(() =>
        {
            //Call BLL Method to retrieve the list of BO.
            return BLLInstance.GetAllList(a,b);
        });
    }


    protected TResult TryAction<TResult>(Func<TResult> action)
    {
        try
        {
            return action();
        }
        catch (Exception e)
        {
            throw;
            // write exception to output (Response.Write(str))
        }
    }

Solution 2

Action is a delegate that has a void return type, so if you want it to return a value, you can't.

For that, you need to use a Func delegate (there are many - the last type parameter is the return type).


If you simply want to have TryAction return a generic type, make it into a generic method:

protected T TryAction<T>(Action action)
{
 try
 {
   action();
 }
 catch(Exception e)
 {
   // write exception to output (Response.Write(str))
 }

 return default(T);
}

Depending on what exactly you are trying to do, you may need to use both a generic method and Func delegate:

protected T TryAction<T>(Func<T> action)
{
 try
 {
   return action();
 }
 catch(Exception e)
 {
   // write exception to output (Response.Write(str))
 }

 return default(T);
}
Share:
19,781
Pravin
Author by

Pravin

Updated on June 16, 2022

Comments

  • Pravin
    Pravin almost 2 years

    In the BLL class, I have written:

    Private List<T> GetData(string a, string b)
    {
       TryAction(()=>{
          //Call BLL Method to retrieve the list of BO.
           return BLLInstance.GetAllList(a,b);
        });
    }
    

    In the BLL Base Class, I have a method:

    protected void TryAction(Action action)
    {
     try
     {
       action();
     }
     catch(Exception e)
     {
       // write exception to output (Response.Write(str))
     }
    }
    

    How can I use TryAction() method with generic return type? please have a suggestion.