#659 – Get Information About an Object’s Type
August 29, 2012 1 Comment
You can call the GetType method of System.Object on any object to get information about that object’s type. Because every type in .NET inherits directly or indirectly from System.Object, every object will have access to the GetType method.
GetType returns an instance of a Type object, which can be queried to learn all about the type of the original object.
static void Main() { Dog kirby = new Dog("Kirby", 13); DumpTypeInfoFor(kirby); int i = 12; DumpTypeInfoFor(i); } private static void DumpTypeInfoFor(object o) { Type t = o.GetType(); Console.WriteLine("Type = {0}", t); Console.WriteLine(" Assembly = {0}", t.Assembly); Console.WriteLine(" BaseType = {0}", t.BaseType); Console.WriteLine(" FullName = {0}", t.FullName); Console.WriteLine(" IsClass = {0}", t.IsClass); Console.WriteLine(" IsValueType = {0}", t.IsValueType); Console.WriteLine(" Properties:"); foreach (PropertyInfo pi in t.GetProperties()) Console.WriteLine(" {0}", pi.Name); Console.WriteLine(" Methods:"); foreach (MethodInfo mi in t.GetMethods()) Console.WriteLine(" {0}", mi.Name); Console.WriteLine(" Events:"); foreach (EventInfo ei in t.GetEvents()) Console.WriteLine(" {0}", ei.Name); Console.WriteLine(" Interfaces:"); foreach (Type ti in t.GetInterfaces()) Console.WriteLine(" {0}", ti.Name); }