#659 – Get Information About an Object’s Type

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);
        }

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #659 – Get Information About an Object’s Type

  1. kai zhou says:

    Good job, thank you Sean.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: