Search Results for

    Show / Hide Table of Contents

    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

    1. Is.TypeOf<T>() checks that actual.GetType() == typeof(T).
    2. For inheritance-aware type checking (like C# is), use InstanceOfTypeConstraint.
    3. null values throw an exception since they have no type.

    See Also

    • InstanceOfType Constraint - Inheritance-aware type checking
    • AssignableTo Constraint - Type assignability check
    • 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