Simplify tuple types using aliases
Si fanúšikom funkcionálneho programovania alebo len rád používaš tuple?
V tom prípade tvoj kód možno vyzerá nejak takto:
static (decimal score, string grade) Grade(decimal score)
=> score switch
{
>= 90M => (score, "A"),
>= 80M => (score, "B"),
>= 70M => (score, "C"),
>= 60M => (score, "D"),
_ => (score, "F")
};
(decimal score, string grade) grade1 = Grade(95M);
static Task<IEnumerable<(decimal score, string grade)>> GetGrades()
=> Task.FromResult(Enumerable.Empty<Grade>());
Od C# 12 môžeme tento a podobný kód zjednodušiť definovaním aliasov pre tuple:
using Grade = (decimal score, string grade);
using Grades = System.Collections.Generic.IEnumerable<(decimal score, string grade)>;
Teraz môžeme tieto aliasy použiť:
static Grade Grade(decimal score)
=> score switch
{
>= 90M => (score, "A"),
>= 80M => (score, "B"),
>= 70M => (score, "C"),
>= 60M => (score, "D"),
_ => (score, "F")
};
Grade grade1 = Grade(95M);
var grade2 = new Grade(91, "A");
static Task<Grades> GetGrades()
=> Task.FromResult(Enumerable.Empty<Grade>());