Search Results for

    Show / Hide Table of Contents

    InstanceOfType Constraint

    InstanceOfTypeConstraint tests that an object is an instance of the specified type or any derived type. This is equivalent to the C# is operator.

    Usage

    Is.InstanceOf(Type expectedType)
    Is.InstanceOf<T>()
    

    Examples

    [Test]
    public void InstanceOfTypeConstraint_Examples()
    {
        // Basic type checking
        Assert.That("Hello", Is.InstanceOf(typeof(string)));
        Assert.That("Hello", Is.InstanceOf<string>());
        Assert.That(42, Is.InstanceOf<int>());
    
        // Inheritance: derived types pass
        Assert.That("Hello", Is.InstanceOf<object>());         // string derives from object
        Assert.That(new List<int>(), Is.InstanceOf<IEnumerable<int>>());
    
        // Interface checking
        Assert.That(new List<int>(), Is.InstanceOf<IList<int>>());
        Assert.That(new Dictionary<string, int>(), Is.InstanceOf<IDictionary<string, int>>());
    
        // Negative tests
        Assert.That("Hello", Is.Not.InstanceOf<int>());
        Assert.That(null, Is.Not.InstanceOf<string>());        // null is not an instance of any type
    }
    

    Notes

    1. Is.InstanceOf<T>() is equivalent to C#'s value is T expression.
    2. For exact type matching (no inheritance), use ExactTypeConstraint.
    3. null always fails Is.InstanceOf for any type.

    See Also

    • ExactType Constraint - Exact type match, no inheritance
    • AssignableTo Constraint - Type assignability check
    • AssignableFrom Constraint - Reverse 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