Wednesday, September 19, 2012

Getting Information About Object's Type

You can get the information of type of the any object by calling the GetType method of System.Object. 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.


For Example:-

 static void Main(string[] args)
  {
          Car objCar=new Car("Wagon R","Red");
          GetTypeInfo(objCar);
            

           int x = 12;
           GetTypeInfo(x);
           Console.ReadLine();

    }
     private static void GetTypeInfo(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);
       }

 

Object Information

No comments:

Post a Comment

^ Scroll to Top