Partilhar via


Newbie Question: How do I figure out the inheritance chain of a type

Redmond_2005_0417_010447

I got this question from someone just starting out on the .NET platform. He is used to hit F12 (go to definition) on types and then figure out the inheritance chain. However, he couldn't do that say on a number (int) or array.

The solution is to write a simple recursive routine as follows

 static void Dump(Type t)
{
    if (t != null)
    {
        Dump(t.BaseType);
        Console.WriteLine(t.ToString());
    }
}

The routine can be called as follows

 Dump(typeof(int));
Dump("abc".GetType());
Dump(1.GetType());
Dump(typeof(EventAttributes));

No marks for guessing the output though :)

Cross posted here...

Comments

  • Anonymous
    November 30, 2007
    Abhinaba, I am a reader of your blog. Thanks for nice posts. I enjoy reading it. Out of curiosity, why one would like to know the base class of primitives (int/long) which are struct (ValueType - Object) Yes, it is useful for reference type, which are complex (System.Windows.Form). Arrays & string which are reference type don't have a big chain. Also, could you describe the use of finding inheritance chain? If it's purely to see the chain, please ignore my comments. Maybe, I am getting into too much :) Reflector can be of help here.

  • Anonymous
    November 30, 2007
    It's purely for academic interest to see it. There is no practical usage :) so I agree to your comment in all respect. As I said, the folks are complete newbies moving in from C++. They were taught about how things inheriting from ValueType are value types themselves. For people moving from C++ if something derives from something they want to see it. E.g. int in C++ is an int, but they got to know that in C# its actually system.Int32 inheriting from System.ValueType, so the natural tendency is to go "Show me that". The code above "show you that"