Find Generic Type - CSharp System.Reflection

CSharp examples for System.Reflection:Type

Description

Find Generic Type

Demo Code

//Copyright (C) Microsoft Corporation.  All rights reserved.
using System.Threading;
using System.Reflection.Emit;
using System.Reflection;
using System.Linq.Expressions;
using System.Text;
using System.Collections.Generic;

public class Main{
        static Type FindGenericType(Type generic, Type type)
        {/*  w  w  w . j  a v  a  2s.  c  om*/
            while (type != null && type != typeof(object))
            {
                if (type.IsGenericType && type.GetGenericTypeDefinition() == generic) return type;
                if (generic.IsInterface)
                {
                    foreach (Type intfType in type.GetInterfaces())
                    {
                        Type found = FindGenericType(generic, intfType);
                        if (found != null) return found;
                    }
                }
                type = type.BaseType;
            }
            return null;
        }
}

Related Tutorials