Search code examples
c#typedefusingnamed

In C#, how to name the type of a tuple with named members? (Like C++ typedef)


this question is not a duplicate of Better naming in Tuple classes than "Item1", "Item2"

In the linked Question, they ask about assigning names to tuple elements. I am asking about naming the entire type which is a tuple with named elements.

I have a tuple with named items in my code:

(string kind, string colour, string length) a = ("annual", "blue", "short);
var myKind = a.kind;
var myColour = a.blue;
var myLength = a.short;

I would like this type to be named so I can use it like this (similar to C++ typedef):

FlowerInformation a = ("annual", "blue", "short);
var myKind = a.kind;
var myColour = a.colour;
var myLength = a.length;

I could use the "using" directive, like so:

using FlowerInformation = System.ValueTuple<string , string , string>;

This way the type has a name, but the items are not named, so my code must become this:

FlowerInformation a = ("annual", "blue", "short);
var myKind = a.Item1;
var myColour = a.Item2;
var myLength = a.Item3;

What I'd really like is a named tuple type with named members. Is it possible in C#?

The following doesn't work:

using FlowerInformation = (string kind, string colour, string length);

Solution

  • Consider using the new record type introduced in C# 9. It is not a Tuple, but if you want a custom type with named fields, it is a viable alternative.

    // Declaration
    record FlowerInformation(string kind, string colour, string length);
    
    // Construction
    FlowerInformation a = new("annual", "blue", "short");
    
    // Accessing a field
    var myKind = a.kind;
    var myColour = a.colour;
    var myLength = a.length;
    
    // Deconstruction
    var (kind, colour, length) = a;
    

    Use record or record class to declare a reference type (similar to Tuple), and record struct to declare a value type (similar to ValueTuple and () syntax).