Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CS0121 compiler error with C# 12 collection expressions for Assert.Equal(T[], T[]) #2812

Closed
martincostello opened this issue Nov 5, 2023 · 1 comment

Comments

@martincostello
Copy link
Contributor

martincostello commented Nov 5, 2023

With xunit 2.6.1 when using C# 12 collection expressions, CS0121 compiler errors occur when using code similar to the following:

[Fact]
public static void CS0121()
{
    int[] actual = [1, 2, 3]; // Assume this value would come from the code being tested
    Assert.Equal([1, 2, 3], actual);
}
CS0121 The call is ambiguous between the following methods or properties: 'Assert.Equal<T>(T[], T[])' and 'Assert.Equal<T>(ReadOnlySpan<T>, Span<T>)'

This can be worked around by using the previous syntax to create a literal array, but this generates an IDE0300 analyser suggestion in Visual Studio to change it back to a collection expression.

[Fact]
public static void No_CS0121()
{
    int[] actual = [1, 2, 3];
    Assert.Equal(new[] { 1, 2, 3 }, actual);
}
IDE0300	Collection initialization can be simplified

Otherwise, the workaround is to assign the expected value to a variable:

[Fact]
public static void Also_No_CS0121()
{
    int[] actual = [1, 2, 3];
    int[] expected = [1, 2, 3];
    Assert.Equal(expected, actual);
}

This issue is similar to #2811, so this might be a duplicate of that, but I only ran into this after updating existing tests to use C# 12 and adopting collection expressions.

martincostello added a commit to martincostello/lambda-test-server that referenced this issue Nov 5, 2023
Add workaround for xunit/xunit#2812.
@bradwilson
Copy link
Member

Unfortunately there will always be cases of compiler ambiguity given the number of overloads the Assert.Equal has. Removing some of those overloads is not really an option.

martincostello added a commit to martincostello/lambda-test-server that referenced this issue Nov 9, 2023
Add workaround for xunit/xunit#2812.
@bradwilson bradwilson closed this as not planned Won't fix, can't repro, duplicate, stale Dec 22, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants