FindCommonAncestor

        public static Type FindCommonAncestor (this Type type, Type targetType)
        {
            if (targetType.IsAssignableFrom(type))
                return targetType;
 
            var baseType = targetType.BaseType;
            while(baseType != null && !baseType.IsPrimitive)
            {
                if (baseType.IsAssignableFrom(type))
                    return baseType;
                baseType = baseType.BaseType;
            }
            return null;
        }
Example:
target.GetType().FindCommonAncestor(Source.GetType());

Description

Finds the nearest common ancestor for type based on the inheritance hierarchy.

Details

Double click on the code to select all.

 

;