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

How to use the GetType method?


C# C# 
Ratings:
0 Comment(s)
 2332  View(s)
Rate this:

How to use the GetType method

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 usethe 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


Don't want to miss updates? Please click the below button!

Follow MindStick