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(object expected)
    Is.Not.SameAs(object expected)
    

    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. For value types, Is.SameAs will always fail because value types are boxed into different objects.
    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