Search Results for

    Show / Hide Table of Contents

    AssignableFrom Constraint

    AssignableFromConstraint tests that an instance of the specified type can be assigned to the actual value's type. In other words, the actual value's type is a base type or interface of the expected type.

    Usage

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

    Examples

    [Test]
    public void AssignableFromConstraint_Examples()
    {
        // A string variable can be assigned from string
        Assert.That("Hello", Is.AssignableFrom(typeof(string)));
        Assert.That("Hello", Is.AssignableFrom<string>());
    
        // An object variable can be assigned from string (string derives from object)
        Assert.That(new object(), Is.AssignableFrom<string>());
    
        // An IEnumerable variable can be assigned from List<int>
        IEnumerable<int> items = new List<int>();
        Assert.That(items, Is.AssignableFrom<List<int>>());
    
        // Negative: an int variable cannot be assigned from string
        Assert.That(5, Is.Not.AssignableFrom(typeof(string)));
    }
    

    Notes

    1. Is.AssignableFrom<T>() is true when actualType.IsAssignableFrom(typeof(T)).
    2. This tests "can I assign an instance of T to this variable?".
    3. This is the reverse of AssignableToConstraint.

    See Also

    • AssignableTo Constraint - Reverse direction check
    • InstanceOfType Constraint - Test if object is instance of type
    • ExactType Constraint - Test for exact type match
    • 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