ValueTuples allow for compiler aliases for their public fields (Item1, Item2, etc...). For example:
var tuple = (Name:"apple",Date:DateTime.Now);
var nameFieldValue = tuple.Name;//"apple"
//here tuple.Name is a compiler alias for tuple.Item1
Is there any way I can do the same thing via reflection?
var tuple = (Name:"apple",Date:DateTime.Now);
var nameFieldValue = tuple.GetType().GetField(nameof(tuple.Name)).GetValue(tuple);//null reference exception (the field is null)
I know I can do this:
var tuple = (Name:"apple",Date:DateTime.Now);
var nameFieldValue = tuple.GetType().GetField("Item1").GetValue(tuple);//"apple"
But I need to get the public fields based on their compiler aliases (tuple.Name), not the actual field names (tuple.Item1).
Tuple value names are a C# language construct akin to local variables and have no existence after the code is compiled.
The compiler will translate:
to:
and if you assign that tuple to another tuple with the same structure:
the complier will just generate this code:
Try or yourself on https://sharplab.io/