Get Type for parameter constraints on the current generic type in CSharp

Description

The following code shows how to get Type for parameter constraints on the current generic type.

Example


using System;/*from  w w  w .j a  v a2s .  co  m*/
using System.Reflection;

public interface ITest {}
public class Base {}
public class Test<T,U> 
    where T : Base, ITest 
    where U : class, new() {}
public class Derived : Base, ITest {}

public class Example
{
    public static void Main()
    {
        Type def = typeof(Test<,>);
        Type[] defparams = def.GetGenericArguments();
        foreach (Type tp in defparams)
        {
            Console.WriteLine("\r\nType parameter: {0}", tp.Name);
            Type[] tpConstraints = tp.GetGenericParameterConstraints();
            foreach (Type tpc in tpConstraints)
            {
                Console.WriteLine("\t{0}", tpc);
            }
        }
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Reflection »




Array
Constructor
Event
Field
Interface
Method
Properties
Type