Search Results for

    Show / Hide Table of Contents

    AssignableTo Constraint

    AssignableToConstraint tests that the actual value can be assigned to a variable of the specified type. In other words, the actual value's type derives from or implements the expected type.

    Usage

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

    Examples

    [Test]
    public void AssignableToConstraint_Examples()
    {
        // A string can be assigned to object (string derives from object)
        Assert.That("Hello", Is.AssignableTo(typeof(object)));
        Assert.That("Hello", Is.AssignableTo<object>());
    
        // A string can be assigned to IEnumerable<char>
        Assert.That("Hello", Is.AssignableTo<IEnumerable<char>>());
    
        // A List<int> can be assigned to IList<int>
        Assert.That(new List<int>(), Is.AssignableTo<IList<int>>());
        Assert.That(new List<int>(), Is.AssignableTo<IEnumerable<int>>());
    
        // Negative: an int cannot be assigned to string
        Assert.That(5, Is.Not.AssignableTo(typeof(string)));
    }
    

    Notes

    1. Is.AssignableTo<T>() is true when typeof(T).IsAssignableFrom(actual.GetType()).
    2. This tests "can this value be assigned to a variable of type T?".
    3. This is the reverse of AssignableFromConstraint.

    See Also

    • AssignableFrom 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