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
Is.SameAsusesobject.ReferenceEquals()internally - it tests object identity, not equality.- For value types,
Is.SameAswill always fail because value types are boxed into different objects. - 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