While investigating the new features in C# 7.x, I created the following class:
using System;
namespace ValueTuples
{
public class Person
{
public string Name { get; }
public DateTime BirthDate { get; }
public Person(string name, DateTime birthDate)
{
Name = name;
BirthDate = birthDate;
}
public void Deconstruct(out string name,
out int year, out int month, out int day)
{
name = Name;
year = BirthDate.Year;
month = BirthDate.Month;
day = BirthDate.Day;
}
public void Deconstruct(out string name,
out int year, out int month,
out (int DayNumber, DayOfWeek DayOfWeek) day)
{
name = Name;
year = BirthDate.Year;
month = BirthDate.Month;
day.DayNumber = BirthDate.Day;
day.DayOfWeek = BirthDate.DayOfWeek;
}
}
}
And the following test code:
using System;
namespace ValueTuples
{
class MainClass
{
static void Main()
{
var dh = new Person("Dennis", new DateTime(1985, 12, 27));
// DECONSTRUCTION:
(string name, _, _, (_, DayOfWeek dow)) = dh;
Console.WriteLine($"{name} was born a {dow}");
}
}
}
If the Person class includes only the SECOND Deconstruct overload, the code compiles and runs fine ("Dennis was born a Friday"). But as soon as the first overload is added to Person, the compiler starts complaining, the error message being:
The call is ambiguous between the following methods or properties: 'Person.Deconstruct(out string, out int, out int, out int)' and 'Person.Deconstruct(out string, out int, out int, out (int DayNumber, DayOfWeek DayOfWeek))' (CS0121) (ValueTuples)
I've read the MSDN and GitHub documentation, but it is not clear to me why the compiler cannot determine that the only applicable overload is the second, given the inner tuple pattern on the left side of the assignment. Any clarification will be appreciated.
See Question&Answers more detail:os