views:

113

answers:

2

In .NET using the GetType function returns the concrete class type of the object. The problem is that i don't know what the type is going to be until runtime, but i do know from which abstract class its derives ( I am using abstract factories to create the adequate class).

How can i get the actual abstract class type? Is it even possible?

+10  A: 

Type.BaseType will tell you the type from which the current type derives. You could recursively call Type.BaseType until Type.IsAbstract is true.

static class TypeExtensions {
    public static Type GetFirstAbstractBaseType(this Type type) {
        if (type == null) {
            throw new ArgumentNullException("type");
        }
        Type baseType = type.BaseType;
        if (baseType == null || baseType.IsAbstract) {
            return baseType;
        }
        return baseType.GetFirstAbstractBaseType();
    }

Usage:

Type abstractBase = typeof(Derived).GetFirstAbstractBaseType();
Jason
+1 for the "first abstract parent" clarification.
Austin Salonen
It would be more consistent with other `Type` methods to return `null` if no ABC is found. (e.g. `BaseType`, `GetNestedType`, `GetElementType`, etc.).
280Z28
@280Z28: Good point. Thanks!
Jason
To second 280Z28 ... you would get a ArgumentNullException for types not deriving from any abstract class.
Daniel Brückner
@Daniel Brückner: Sorry, I'm not following you. I think my code will return `null` for any class that does not have an abstract base.
Jason
@280Z28: I agree with the edit but I do not agree with throwing a `NullReferenceException`. An `ArgumentNullException` better describes the exceptional situation; a `NullReferenceException` would be misleading as we didn't actually try to dereference a `null` reference. In fact, I think there is no reason to ever throw a `NullReferenceException`; the CLR can do that.
Jason
+1: For calling the class TypeExtensions. Oh, and I renamed the method for the same reason as it returning null. :)
280Z28
@Jason You are right both times - I misread the code and really never throw NullReferenceExceptions.
Daniel Brückner
I missed that you are looking at type and type.BaseType and read the code as return (type == null) || type.IsAbstract ? type : type.GetFirstAbstractBaseType(); But this is slightly different because when called on an abstract type it returns this type instead of the first abstract base type.
Daniel Brückner
A: 

I think you are looking for the BaseType property off the Type class. This gets the type your current type directly inherits from.

confusedGeek