Use a C# record type to declare a reusable tuple type (DRY)

 Use a record type to declare a reusable tuple type (DRY)

Following the DRY principle (Don't Repeat Yourself), we want to avoid repeating the same tuple declarations in our code. This aligns with Clean Code (avoid duplicate code).

Example - several methods all share the same tuple structure:

void LogTransaction( (double amount, DateTime date, string summary) ) { }
void ProcessTransaction( (double amount, DateTime date, string summary) ) { }
void ValidateTransaction( (double amount, DateTime date, string summary) ) { }

For a class or namespace, we can use the using keyword to avoid such duplications:

using MyDictionary = Dictionary<string, string>;
using MyTests = Application.ModuleOne.Tests;


But this is not possible with a tuple.

Instead, we can use the record type introduced in C# 9:

record Transaction(double amount, DateTime date, string summary);

Now, we can rewrite our code to avoid the duplication:

void LogTransaction( Transaction transaction ) { }
void ProcessTransaction( Transaction transaction ) { }
void ValidateTransaction( Transaction transaction ) { }

The calling code only needs minimal changes.

Comments