Search code examples
c#resharperc#-6.0fluent-assertionsnameof

Why does nameof() give an ambiguous invocation warning in a Linq expression, but not when I use the same value as a string?


I'm getting a compiler warning that started happening when I upgraded to FluentAssertions 4.2.2. In the following code, if I call EndsWith(nameof(x)), I get an ambiguous invocation warning. If instead I define var foo = nameof(x) and call EndsWith(foo), it compiles cleanly. The code runs ok in both scenarios.

My questions are why is this happening, and is there a workaround other than storing the nameof() result in a variable?

[Test]
public void TestLastNamesAreSame()
{
    var original = new MyDTO("fred", "jones");
    var expected = new MyDTO("barney", "jones");

    // this gives an Ambiguous invocation warning
    expected.ShouldBeEquivalentTo(original, o => o
        .Excluding(x => x.SelectedMemberPath.EndsWith(nameof(MyDTO.FirstName))));

    // but when I use a variable holding the same value, it works without warning
    const string nameOfFirstNameField = nameof(MyDTO.FirstName);
    expected.ShouldBeEquivalentTo(original, o => o
        .Excluding(x => x.SelectedMemberPath.EndsWith(nameOfFirstNameField)));
}

public class MyDTO
{
    public string FirstName { get; }
    public string LastName { get; }

    public MyDTO(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = lastName;
    }
}

Solution

  • Are you sure that this is a compiler error/warning and not a ReSharper warning?

    If it is the former, what is the CSNNNN error/warning number?

    Have look at (Resharper: Ambiguous Invocation)