C# Type GetGenericArguments

Description

Type GetGenericArguments returns an array of Type objects that represent the type arguments of a generic type or the type parameters of a generic type definition.

Syntax

Type.GetGenericArguments has the following syntax.


public virtual Type[] GetGenericArguments()

Returns

Type.GetGenericArguments method returns

Example

The following code example uses the GetGenericArguments method to display the type arguments of a constructed type and the type parameters of its generic type definition.


using System;//from   w  w w  .  ja  va 2s .com
using System.Reflection;
using System.Collections.Generic;

public class Base<T, U> { }

public class Derived<V> : Base<int, V> { }

public class Test
{
    public static void Main()
    {
        Type t = typeof(Derived<>);

        if (t.IsGenericType)
        {
            Type[] typeArguments = t.GetGenericArguments();
        
            Console.WriteLine(typeArguments.Length);
        
            foreach (Type tParam in typeArguments)
            {
                if (tParam.IsGenericParameter)
                {
                    Console.WriteLine("\t\t{0}\t(unassigned - parameter position {1})",
                        tParam,
                        tParam.GenericParameterPosition);
                }
                else
                {
                    Console.WriteLine("\t\t{0}", tParam);
                }
            }
        }
    }
}

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