liveBook · Manning

Named tuple

As explained in .NET in Action, Second Edition

A named tuple is a C# tuple whose elements have programmer-defined names in addition to positional access.

A named tuple groups related values without declaring a class or struct. In C#, a tuple can give its elements names; unnamed elements are accessed as Item1, Item2, and so on. section 3.1.1

Listing 3.13 Modifying AllFonts to return a tuple
public static
  Lazy<IEnumerable<(string Name, FiggleFont Font)>>    #1
  AllFonts = new (() =>
    from p in typeof(FiggleFonts)
      .GetProperties(
        BindingFlags.Public | BindingFlags.Static)
    select (                                           #1
      Name: p.Name,                                    #2
      Font: (p.GetValue(null) as FiggleFont)           #3
    ));

AllFonts returns pairs of font names and FiggleFont objects. The declared tuple type names the elements Name and Font, and the LINQ projection supplies their values. section 3.1.1

Keeping both values lets a request filter and sort by Name while checking Font.Direction. It avoids creating a separate type just to carry the pair through the query. section 3.1.1

How .NET in Action, Second Edition covers it

How deep it goes
Defines named and unnamed tuple elements and shows a typed LINQ projection, without exploring tuple internals.
Examples
Uses an AllFonts collection pairing reflected property names with FiggleFont objects.
What it assumes
Assumes familiarity with C# properties and LINQ while explaining tuple field names.
What you can do after
Apply it via C# named tuples to carry related values through a LINQ query without declaring a new type.
How it connects
Connects tuples to LINQ projections, reflection, and ASP.NET Core request handling.

Also explained in

Compare how 3 books explain named tuple →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of .NET in Action, Second Edition. The section links point to the parts of the book it draws on.