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.
If you want to return a value, you need to use System. Func<T>. Basically, System. Action (and Action<T>, Action<T1,T2>, etc) are intended as delegates for methods that don't return values.
Action is a delegate type defined in the System namespace. An Action type delegate is the same as Func delegate except that the Action delegate doesn't return a value. In other words, an Action delegate can be used with a method that has a void return type.
delegate: It is the keyword which is used to define the delegate. return_type: It is the type of value returned by the methods which the delegate will be going to call. It can be void. A method must have the same return type as the delegate.
Inside the C# function, the value to be returned is given by the expression in the return statement. Since the function returns data, and all data in C# is typed, there must be a type given for the value returned. Note that the function heading does not start with static void. In place of void is int.
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))
}
}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With