Mono Class Library: System.Type Overview | Members

System.Type.IsAssignableFrom Method

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

public virtual bool IsAssignableFrom (Type c)

Parameters

c
The Type to compare with the current Type .

Returns

false if c is a null reference.

true if one or more of the following statements are true; otherwise false.

  • If c and the current Type represent the same type.
  • If the current Type is in the inheritance hierarchy of c.
  • If the current Type is an interface and c supports that interface.
  • If c is a generic type parameter and the current instance represents one of the constraints of c.

Remarks

Note:

A generic type definition is not assignable from a closed constructed type.

Example

The following example demonstrates the Type.IsAssignableFrom(Type) method using arrays.

C# Example

using System;
class ArrayTypeTest {
 public static void Main() {
 int i = 1;
 int [] array10 = new int [10];
 int [] array2 = new int[2];
 int [,]array22 = new int[2,2];
 int [,]array24 = new int[2,4];
 int [,,]array333 = new int[3,3,3];
 Type array10Type = array10.GetType();
 Type array2Type = array2.GetType();
 Type array22Type = array22.GetType();
 Type array24Type = array24.GetType();
 Type array333Type = array333.GetType();

 // If X and Y are not both arrays, then false
 Console.WriteLine("int[2] is assignable from int? {0} ", array2Type.IsAssignableFrom(i.GetType()));
 // If X and Y have same type and rank, then true.
 Console.WriteLine("int[2] is assignable from int[10]? {0} ",  array2Type.IsAssignableFrom(array10Type));
 Console.WriteLine("int[2,2] is assignable from int[2,4]? {0}",  array22Type.IsAssignableFrom(array24Type));
 Console.WriteLine("int[2,4] is assignable from int[2,2]? {0}",  array24Type.IsAssignableFrom(array22Type));
 Console.WriteLine("");
 // If X and Y do not have the same rank, then false.
 Console.WriteLine("int[2,2] is assignable from int[10]? {0}",  array22Type.IsAssignableFrom(array10Type));
 Console.WriteLine("int[2,2] is assignable from int[3,3,3]? {0}",  array22Type.IsAssignableFrom(array333Type));
 Console.WriteLine("int[3,3,3] is assignable from int[2,2]? {0}",  array333Type.IsAssignableFrom(array22Type));
 }
}

The output is

int[2] is assignable from int? False
int[2] is assignable from int[10]? True
int[2,2] is assignable from int[2,4]? True
int[2,4] is assignable from int[2,2]? True
int[2,2] is assignable from int[10]? False
int[2,2] is assignable from int[3,3,3]? False
int[3,3,3] is assignable from int[2,2]? False

Requirements

Namespace: System
Assembly: mscorlib (in mscorlib.dll)
Assembly Versions: 1.0.5000.0, 2.0.0.0