Overview
C# 7 now supports function and method that return multiple values.
The reasons why I like it are
- Output parameter require more code to write and do not make the code easier to read
- The other solution is to create a specific class that contains all the values. It is clean but require more code.
- The Python language had this feature for a long time based on the concept of Tuple.
- A previous version of C# introduced the concept of Tuple, but all the names had to be Item1, Item2.
In C# 7 there is a new Tuples concept. For more about it see link Tuples with C# 7.0.
Async Method
The more tricky question is how is this supposed to work with async method.
public async Task < ( DonationDTO donationDTO, string messageId ) > DequeueAsync()
{
var m = await _queueManager.DequeueAsync();
if(m == null)
{
return ( null, null );
}
else
{
base.TrackNewItem();
var donationDTO = DonationDTO.FromJSON(m.AsString);
return ( donationDTO, m.Id );
}
}
// How to call the method - Solution 1
var result = await donationQueue.DequeueAsync();
var donationDTO = result.donationDTO;
var messageId = result.messageId;
// How to call the method - Solution 2
(DonationDTO donationDTO, string messageId) = await donationQueue.DequeueAsync();
No comments:
Post a Comment