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

SameAs should warn if used with value types #276

Closed
jnm2 opened this issue Aug 6, 2020 · 3 comments · Fixed by #278
Closed

SameAs should warn if used with value types #276

jnm2 opened this issue Aug 6, 2020 · 3 comments · Fixed by #278
Assignees
Milestone

Comments

@jnm2
Copy link
Contributor

jnm2 commented Aug 6, 2020

Motivation: nunit/nunit#3614 (comment)

If either the expected value or actual value or both are a value-typed expression, Assert.AreSame or Is.SameAs are guaranteed to fail because C# will implicitly convert the value type to a new boxed instance. It doesn't make sense to use AreSame/SameAs unless the types of the passed expressions are both reference types.

It would make sense to offer a fix to change SameAs to EqualTo since that was probably the intent.

Should show an error or warning on SameAs:

class C
{
    void M()
    {
        var x = 3;
        Assert.That(x, Is.SameAs(3));

        // Also this
        Assert.That((object)x, Is.SameAs(3));

        // Also this
        Assert.That(x, Is.SameAs((object)3));
    }
}

Should not show an error or warning because the expressions are both reference-typed:

class C
{
    void M()
    {
        var x = 3;
        Assert.That((object)x, Is.SameAs((object)3));
    }
}
@manfred-brands
Copy link
Member

I will work on this over the weekend.

@manfred-brands
Copy link
Member

Analyzer and UnitTest done. Code Fix pending.

@manfred-brands
Copy link
Member

Code Fix and documentation done.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants