ExtensionMethod.NET Home of 818 C#, Visual Basic, F# and Javascript extension methods

FindCommonAncestor

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

Source

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());

Author: David Hanson

Submitted on: 14 jan 2010

Language: C#

Type: System.Type

Views: 2388