C# Type IsAssignableFrom

Description

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

Syntax

Type.IsAssignableFrom has the following syntax.


public virtual bool IsAssignableFrom(
  Type c
)

Parameters

Type.IsAssignableFrom has the following parameters.

  • c - The type to compare with the current type.

Returns

Type.IsAssignableFrom method returns 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, or if c represents a value type and the current Type represents Nullable<c> (Nullable(Of c) in Visual Basic). false if none of these conditions are true, or if c is null.

Example

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


//from  w w w . j  a  v  a 2s .c  o  m
using System;
using System.Collections.Generic;
class Program
{
    public static void Main()
    {
            // Note that "int?[]" is the same as "Nullable<int>[]" 
            int?[] arrayNull = new int?[10];
            List<int> genIntList = new List<int>();

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

            Console.WriteLine(genIntListType.IsAssignableFrom(arrayNullType));
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System »




Array
BitConverter
Boolean
Byte
Char
Console
ConsoleKeyInfo
Convert
DateTime
DateTimeOffset
Decimal
Double
Enum
Environment
Exception
Guid
Int16
Int32
Int64
Math
OperatingSystem
Random
SByte
Single
String
StringComparer
TimeSpan
TimeZone
TimeZoneInfo
Tuple
Tuple
Tuple
Type
UInt16
UInt32
UInt64
Uri
Version