I have a class that has a number of methods that follow the below pattern:
public void GetSomeData1(DataParameters[] parameters, Action responseHandler)
{
_getSomeData1ResponseHandler = responseHandler;
Transactions.GetSomeData1(SomeData1ResponseHandler, parameters);
}
private void SomeData1ResponseHandler(Response response)
{
if (response != null)
{
CreateSomeData1(response.Data);
}
}
public void CreateSomeData1(Data data)
{
//Create the objects and then invoke the Action
...
if(_getSomeData1ResponseHandler != null)
{
_getSomeData1ResponseHandler();
}
}
So, some external class calls GetSomeData1 and passes in an Action, which should be called when the data is available. GetSomeData1 stores the response Action and calls Transactions.GetSomeData1 (an async call). Once that async call is finished, the data is created and the original passed in Action is called.
The thing is, for every different GetSomeData call I have, I need to store the passed in Action so I can reference it later. Is there a way I can somehow pass the original Action to the final method (CreateSomeData1) without storing it?
Thanks.
You can pass the data along as a captured variable with lambda expressions. No need for class fields.
Internally, the compiler will create classes and fields to hold the data, but the code you write is cleaner and easier to maintain.