blog

Home / DeveloperSection / Blogs / How to use the GetType method?

How to use the GetType method?

Amit Singh4100 09-Feb-2011

GetType is the basis for usingreflection in .NET. It returns a Type object, describing the object it was calledon. It can then be used to extract type member data like methods and fieldsthat may subsequently be used for late-bound method invocations. The GetType method is also useful if we getan object at runtime and we do not know what its type is. We can use thereturned Type object to figure out what to do with the object.

how to use the GetType method.

Example:
class Employee
{ }
class Class1
{
   static void Main()
   {
        object emp1 = new Employee();
        Employeeemp2 = new Employee();
        Console.WriteLine(emp1.GetType());
        Console.WriteLine(emp2.GetType());
        Console.ReadLine();
    }
}


Note:


There aretwo instances of the Employee class created in the Main method. The first isassigned to a reference of type object and the second is assigned to areference of type Employee. When we run, the program will print “Employee” asthe result of the call to GetType. This shows that GetType returns the run-timetype of the object it is called on, rather than the compile-time reference itis assigned to. 


Output:

Employee

Employee


Updated 18-Sep-2014

Leave Comment

Comments

Liked By