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.
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
NullReferenceExceptionif you try to access a property like.Nameat the end when the result isnull.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 calledTypeChain:There would be a few changes to the
FindBaseClassWithstatic implementations: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 returnnull, or if any are notnull, then purge all thenullentries first before processing so they don’t pollute the result. This can be extended of course to any desired logic.