ExactType Constraint
ExactTypeConstraint tests that an object is exactly the specified type, not a derived type.
Usage
Is.TypeOf(Type expectedType)
Is.TypeOf<T>()
Examples
[Test]
public void ExactTypeConstraint_Examples()
{
// Exact type match
Assert.That("Hello", Is.TypeOf(typeof(string)));
Assert.That("Hello", Is.TypeOf<string>());
Assert.That(42, Is.TypeOf<int>());
// Derived types fail - exact match required
Assert.That("Hello", Is.Not.TypeOf<object>()); // string is not exactly object
Assert.That(new List<int>(), Is.TypeOf<List<int>>());
Assert.That(new List<int>(), Is.Not.TypeOf<IList<int>>()); // List<int> is not exactly IList<int>
// Common use: distinguish between value types
Assert.That(42, Is.TypeOf<int>());
Assert.That(42L, Is.TypeOf<long>());
Assert.That(42L, Is.Not.TypeOf<int>());
}
Notes
Is.TypeOf<T>()checks thatactual.GetType() == typeof(T).- For inheritance-aware type checking (like C#
is), use InstanceOfTypeConstraint. nullvalues throw an exception since they have no type.
See Also
- InstanceOfType Constraint - Inheritance-aware type checking
- AssignableTo Constraint - Type assignability check