Type.IsAssignableFrom Method

Expand
Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.
0 out of 1 rated this helpful - Rate this topic
.NET Framework Class Library

Type.IsAssignableFrom Method

Determines whether an instance of the current Type can be assigned from an instance of the specified Type.

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)
public virtual bool IsAssignableFrom(
	Type c
)

Parameters

c
Type: System.Type
The type to compare with the current type.

Return Value

Type: System.Boolean
true if c and the current Type represent the same type, or if the current Type is in the inheritance hierarchy of c, or if the current Type is an interface that c implements, or if c is a generic type parameter and the current Type represents one of the constraints of c. false if none of these conditions are true, or if c is Nothing.

Implements

_Type.IsAssignableFrom(Type)

This method can be overridden by a derived class.

Note Note

A generic type definition is not assignable from a closed constructed type. That is, you cannot assign the closed constructed type MyGenericList<int> (MyGenericList(Of Integer) in Visual Basic) to a variable of type MyGenericList<T>.

You can determine the element types of a Type using GetElementType.

If the c parameter is of type TypeBuilder, the result is based on the type that is to be built. The following code example demonstrates this using a built type named B.

TypeBuilder b1 = moduleBuilder.DefineType("B", TypeAttributes.Public, typeof(A));
// Returns true:
typeof(A).IsAssignableFrom(b1))

The following example demonstrates the IsAssignableFrom method using defined classes, integer arrays, and generics.


using System;
using System.Collections.Generic;
class Program
{
    public static void Main()
    {
            // Demonstrate classes:
            Console.WriteLine("Defned Classes:");
            Room room1 = new Room();
            Kitchen kitchen1 = new Kitchen();
            Bedroom bedroom1 = new Bedroom();
            Guestroom guestroom1 = new Guestroom();
            MasterBedroom masterbedroom1 = new MasterBedroom();

            Type room1Type = room1.GetType();
            Type kitchen1Type = kitchen1.GetType();
            Type bedroom1Type = bedroom1.GetType();
            Type guestroom1Type = guestroom1.GetType();
            Type masterbedroom1Type = masterbedroom1.GetType();

            Console.WriteLine("room assignable from kitchen: {0}", room1Type.IsAssignableFrom(kitchen1Type));
            Console.WriteLine("bedroom assignable from guestroom: {0}", bedroom1Type.IsAssignableFrom(guestroom1Type));
            Console.WriteLine("kitchen assignable from masterbedroom: {0}", kitchen1Type.IsAssignableFrom(masterbedroom1Type));

            // Demonstrate arrays:
            Console.WriteLine();
            Console.WriteLine("Integer arrays:");

            int[] array2 = new int[2];
            int[] array10 = new int[10];
            int[,] array22 = new int[2, 2];
            int[,] array24 = new int[2, 4];

            Type array2Type = array2.GetType();
            Type array10Type = array10.GetType();
            Type array22Type = array22.GetType();
            Type array24Type = array24.GetType();

            Console.WriteLine("int[2] assignable from int[10]: {0}", array2Type.IsAssignableFrom(array10Type));
            Console.WriteLine("int[2] assignable from int[2,4]: {0}", array2Type.IsAssignableFrom(array24Type));
            Console.WriteLine("int[2,4] assignable from int[2,2]: {0}", array24Type.IsAssignableFrom(array22Type));

            // Demonstrate generics:
            Console.WriteLine();
            Console.WriteLine("Generics:");

            // Note that "int?[]" is the same as "Nullable<int>[]"
            int?[] arrayNull = new int?[10];
            List<int> genIntList = new List<int>();
            List<Type> genTList = new List<Type>();

            Type arrayNullType = arrayNull.GetType();
            Type genIntListType = genIntList.GetType();
            Type genTListType = genTList.GetType();

            Console.WriteLine("int[10] assignable from int?[10]: {0}", array10Type.IsAssignableFrom(arrayNullType));
            Console.WriteLine("List<int> assignable from List<Type>: {0}", genIntListType.IsAssignableFrom(genTListType));
            Console.WriteLine("List<Type> assignable from List<int>: {0}", genTListType.IsAssignableFrom(genIntListType));

            Console.ReadLine();

    }
}
class Room
{
}

class Kitchen : Room
{
}

class Bedroom : Room
{
}

class Guestroom : Bedroom
{
}

class MasterBedroom : Bedroom
{
}

//This code example produces the following output:
//
// Defned Classes:
// room assignable from kitchen: True
// bedroom assignable from guestroom: True
// kitchen assignable from masterbedroom: False
//
// Integer arrays:
// int[2] assignable from int[10]: True
// int[2] assignable from int[2,4]: False
// int[2,4] assignable from int[2,2]: True
//
// Generics:
// int[10] assignable from int?[10]: False
// List<int> assignable from List<Type>: False
// List<Type> assignable from List<int>: False


.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Did you find this helpful?
(1500 characters remaining)
Community Additions ADD
Undocumented behavior for Nullable`1

When this type is the Nullable`1 struct, it looks like this method can return True when c is the type of the non-nullable struct wrapped by this type. See this simple example:
   

    static void Main()
{
// OK with reference types
Console.WriteLine(IsAssignable<EventArgs, AssemblyLoadEventArgs>());

// undocumented with nullable value types
Console.WriteLine(IsAssignable<int?, int>());
Console.WriteLine(IsAssignable<DateTime?, DateTime>());
}

static bool IsAssignable<TGeneral, TSpecial>()
{
return typeof(TGeneral).IsAssignableFrom(typeof(TSpecial));

You probably have a good reason for this, but I think it needs to be documented on this page that the method will return True in this case.

/JeppeSN

3/22/2012
Method name ambiguous

The name of the Type.IsAssignableFrom method is vague and confusing when applied to testing inheritance or detecting interface implementations.  The following wrapper for these purposes would make a lot more sense:

        public static bool CanBeTreatedAsType(this Type CurrentType, Type TypeToCompareWith)
        {
            // Always return false if either Type is null
            if (CurrentType == null || TypeToCompareWith == null)
                return false;

            // Return the result of the assignability test
            return TypeToCompareWith.IsAssignableFrom(CurrentType);
        }

Then, one can have more understandable client syntax such as:

        bool CanBeTreatedAs = typeof(SimpleChildClass).CanBeTreatedAsType(typeof(SimpleClass));
        CanBeTreatedAs = typeof(SimpleClass).CanBeTreatedAsType(typeof(IDisposable));

The advantage of this method instead of the 'is' keyword is that it can be used at run-time to test unknown, arbitrary Types, whereas the 'is' keyword (and a generic Type parameter) requires compile-time knowledge of specific Types.

10/26/2011
The opposite of "is"
It is a bit confusing to figure out which way around to put the parameters. Put them in the opposite order to "is":

if (a is b)

would become

if (typeof(b).IsAssignableFrom(a.getType()))
6/25/2011
This method does NOT check that one type is assignable from another!
If you read the conditions under which it returns true they are not the same as being able to assign from one object to another.  For example double is NOT assignable from int according to this method but in C# it clearly is assignable because of implicit casting.  If you are using this method with the primitive number types be careful as it doesn't give the result you'd expect from the name of the method.
6/8/2011