I created a list of tuples with named fields as follows:
var list = new List<(string First, string Last)>();
var lt = (First: "first", Last: "last");
list.Add(lt);
However, when I view the content of the list in VS2019 debugger I can see that field names appear as "Item1" and "Item2".
Is there a way for make List<> to preserve tuple field names?
CodePudding user response:
List
does support named tuples; it's the debugger that's the problem. Named Tuples use "compiler magic" to allow you to reference the custom names at design time, but at compile time the named fields are converted to the default name ItemX
:
From MDSN:
At compile time, the compiler replaces non-default field names with the corresponding default names. As a result, explicitly specified or inferred field names aren't available at run time.
You can still reference the names after pulling an item from the list at design time:
var list = new List<(string First, string Last)>();
var lt = (First: "first", Last: "last");
list.Add(lt);
Console.WriteLine(lt); // "(first, last)"
var x = list[0];
Console.WriteLine(x); // "(first, last)"
// Can still reference the names of a tuple from the list at coding time
Console.WriteLine(x.First); // "first"
Console.WriteLine(x.Item1); // "first"
But at runtime (e.g. when using Reflection) only the default field names will be available:
foreach(var p in x.GetType().GetFields())
{
Console.WriteLine(p.Name);
}
Item1
Item2
It may be possible for the debugger to get the design-time name, but apparently that feature hasn't been built yet.