There are typically 2 ways that we return values from a method, create a custom type or use multiple out parameters. Well, there is another way that this can be achieved and it’s by using a feature introduced in C# 7 called a tuple. A tuple is a value-type that lets you group data into a single object without declaring a separate type.
The PersonService shows how to return a tuple:
public class ValidationStatus
{
public bool IsNameValid { get; set; }
public bool IsAgeValid { get; set; }
public bool IsDateOfBirthValid { get; set; }
public void Deconstruct(out bool nameComplete,
out bool isAgeValid,
out bool isValidDOB)
{
nameComplete = IsNameValid;
isAgeValid = IsAgeValid;
isValidDOB = IsDateOfBirthValid;
}
}
public class PersonService
{
public
(bool isNameValid, bool isAgeValid, bool isDateOfBirth)
PreparePerson()
{
ValidationStatus status = Validate();
(bool isNameValid, bool isAgeValid, bool isDateOfBirthValid) = status;
return (isNameValid, isAgeValid, isDateOfBirthValid);
}
ValidationStatus Validate()
{
return new ValidationStatus
{
IsNameValid = true,
IsAgeValid = true,
IsDateOfBirthValid = true
};
}
}
And Here’s how to consume the tuple:
class Program
{
readonly PersonService personSvc = new PersonService();
static void Main(string[] args)
{
new Program().Start();
}
void Start()
{
(bool isNameValid, bool isAgeValid, bool isDateOfBirthValid) =
personSvc.PreparePerson();
Console.WriteLine(
$"\nPerson Status:\n\n" +
$"Is Name Valid? {isNameValid}\n" +
$"Is Age Valid? {isAgeValid}\n" +
$"Is Date Of Birth Valid? {isDateOfBirthValid}\n\n";
}
}
Conclusion:
The solution implementation of PreparePerson shows the mechanics of work‐
ing with tuples.