Search Results for

    Show / Hide Table of Contents

    SameAs Constraint

    SameAsConstraint tests whether the actual value is the same object instance as the expected value (reference equality). This is different from Is.EqualTo, which tests for value equality.

    Usage

    Is.SameAs<T>(T? expected) where T : class?
    Is.Not.SameAs<T>(T? expected) where T : class?
    

    Is.SameAs only accepts reference types. Using it with a value type, such as an int or an int?, is a compiler error. Use Is.EqualTo for value types.

    Note

    In NUnit 4 and earlier, the signature was Is.SameAs(object expected). It also accepted value types, but the assertion always failed, because value types are boxed into different objects.

    Examples

    [Test]
    public void SameAsConstraint_Examples()
    {
        var obj1 = new object();
        var obj2 = obj1;
        var obj3 = new object();
    
        // Same reference
        Assert.That(obj2, Is.SameAs(obj1));
    
        // Different objects (even if equal)
        Assert.That(obj3, Is.Not.SameAs(obj1));
    
        // String interning example
        var str1 = "Hello";
        var str2 = "Hello";
        Assert.That(str2, Is.SameAs(str1));  // Interned strings are same reference
    }
    

    Notes

    1. Is.SameAs uses object.ReferenceEquals() internally - it tests object identity, not equality.
    2. Is.SameAs can't be used with value types. The compiler rejects them.
    3. Use Is.EqualTo when you want to compare values; use Is.SameAs when you need to verify the exact same instance.

    See Also

    • Equal Constraint - For value equality
    • Edit this page
    In this article
    Back to top Generated by DocFX | Copyright (c) 2018- The NUnit Project - Licensed under CC BY-NC-SA 4.0