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
Is.SameAsusesobject.ReferenceEquals()internally - it tests object identity, not equality.Is.SameAscan't be used with value types. The compiler rejects them.- Use
Is.EqualTowhen you want to compare values; useIs.SameAswhen you need to verify the exact same instance.
See Also
- Equal Constraint - For value equality