1

Suppose I have following class:

public class Xyz {
}

public class Abc: Xyz {
}

public class Pqr: Xyz {
}

public class Wtf: Abc {
}

with a method to find the common base type of type1 and type2:

public static Type FindBaseClassWith(this Type type1, Type type2);

Then, I call the method with:

typeof(Wtf).FindBaseClassWith(variousType).FindBaseClassWith(typeof(Xyz));

Where variousType is a variable of Type, it possibly sometimes be null.

And FindBaseClassWith is meant to be chained call like:

t1.FindBaseClassWith(t2).FindBaseClassWith(t3).FindBaseClassWith(t4);

to find the only base type between them.

What should the method FindBaseClassWith return?

A most acceptable answer will be mark whether it will be the solution.

Ken Kin
  • 4,503
  • 3
  • 38
  • 76
  • possible duplicate of [Evaluate the maximum possible type to fit both of types](http://stackoverflow.com/questions/14107683/evaluate-the-maximum-possible-type-to-fit-both-of-types) – mellamokb Jan 16 '13 at 14:32
  • Is your question how to avoid NPE in case one member of the chain is `null`? Since it's an extension method, it will work fine even if one of the members of the chain is `null`. You can call extension methods on a `null` reference because it's syntactic sugar for a method call where the object is passed as a parameter. – mellamokb Jan 16 '13 at 14:37
  • Have a look at the accepter answer of [this question][1]. [1]: http://stackoverflow.com/questions/353430/easiest-way-to-get-a-common-base-class-from-a-collection-of-types – Tommaso Belluzzo Jan 16 '13 at 14:39
  • 1
    Isn't `FindBaseClassWith` transitive, i.e., you could combine them in any order or combination, and the result would be the same? Why can't the operation apply to `t1` and `t2`, giving result `t12`, then combined with `t3`, giving result `t123`, then combined with `t4`, giving result `t1234` which is the most derived base type underlying them all? Why does there need to be any different logic because they are chained together? – mellamokb Jan 16 '13 at 14:47
  • 1
    @KenKin: You can already do chained call `t1.FindBaseClassWith(t2).FindBaseClassWith(t3).FindBaseClassWith(t4);` just fine with the other answer you have. So you're problem is there's a situation in which the result is *incorrect* if it doesn't take into account all four types at once? Can you provide an example where the answer to your other question returns a different result than the result you expect? – mellamokb Jan 16 '13 at 14:53
  • @mellamokb: I understand what you say about extension method, it won't throw NRE, that's not the problem. If you have a answer, just post, comments can not marked accepted, thanks. – Ken Kin Jan 16 '13 at 15:01
  • @KenKin: I'd post an answer, but I don't think I yet understand the question :) – mellamokb Jan 16 '13 at 15:03
  • @mellamokb: The sample is posted in the question body. This is a re-thinking from the scratch, and try to redefine the `FindBaseClassWith`. – Ken Kin Jan 16 '13 at 15:06

2 Answers2

2

Since it's an extension method, it will work fine even if one of the members of the chain is null. You can call extension methods on a null reference because it's syntactic sugar for a method call where the object is passed as a parameter. However, you will get a NullReferenceException if you try to access a property like .Name at the end when the result is null.

If you want to use a chain call to collect a series of parameters, and then only "process" them at the end, you want a similar pattern to LINQ. The intermediate types should be some sort of a wrapper that simply collects the values in the chain. Then there should be a final call that actually initiates the process of matching the types, i.e., something like .Resolve(). Here's an example implementation called TypeChain:

public class TypeChain
{
    private List<Type> types;

    public TypeChain(Type t)
    {
        types = new List<Type>();
        types.Add(t);
    }

    // searching for common base class (either concrete or abstract)
    public TypeChain FindBaseClassWith(Type typeRight)
    {
        this.types.Add(typeRight);
        return this;
    }

    public Type Resolve()
    {
        // do something to analyze all of the types
        if (types.All (t => t == null))
            return null;
        else
            types = types.Where (t => t != null).ToList();

        var temp = types.First();
        foreach (var type in types.Skip(1))
        {
            temp = temp.FindBaseClassWithHelper(type);
        }
        return temp;
    }
}

There would be a few changes to the FindBaseClassWith static implementations:

// searching for common base class (either concrete or abstract)
public static Type FindBaseClassWithHelper(this Type typeLeft, Type typeRight)
{
    if(typeLeft == null || typeRight == null) return null;

    return typeLeft
            .GetClassHierarchy()
            .Intersect(typeRight.GetClassHierarchy())
            .FirstOrDefault(type => !type.IsInterface);
}

// searching for common base class (either concrete or abstract)
public static TypeChain FindBaseClassWith(this Type typeLeft, Type typeRight)
{
    return new TypeChain(typeLeft).FindBaseClassWith(typeRight);
}

Using the chaining logic above allows for a logic scenario that isn't possible with the original code. It's now possible to check if all entries are null, and then return null, or if any are not null, then purge all the null entries first before processing so they don't pollute the result. This can be extended of course to any desired logic.

mellamokb
  • 56,094
  • 12
  • 110
  • 136
  • Thank you very much. I'm sure it can be done with your class, but it's the case I thought expensive. – Ken Kin Jan 16 '13 at 15:30
  • Is `typeof(Wtf).FindBaseClassWith(variousType).FindBaseClassWith(typeof(Xyz));` the case/example you keep referring to? First of all, you haven't explained what `variousType` is, or what the expected output is. Secondly, I just ran that code in a loop 1,000,000 times using the code from your related question, and it completes in 1.2 seconds. What exactly is expensive about this? What is your specific performance issue you are having? – mellamokb Jan 16 '13 at 15:41
1

See http://msdn.microsoft.com/en-us/library/system.type.basetype.aspx

You can write a recursive function to transverse the hierarchy by repeatedly comparing BaseType with the desired type.

Dustin Kingen
  • 20,677
  • 7
  • 52
  • 92
  • @KenKin It would be a lot easier to write the `FindBaseClassWith` using params like `public static Type FindBaseClassWith(this Type t, params Type[] commonTypes)` – Dustin Kingen Jan 16 '13 at 14:48
  • @KenKin: Can you post some sample code of your real-world use case? That might help understand what solution you're looking for. – mellamokb Jan 16 '13 at 15:23