Difference Between Typeof and GetType() Methods

Ever wondered in the world of programming, when you want to know the details of an assembly containing a type.

Let’s consider an example.

Consider a Type Employee defined in some assembly X. Employee instance is used in an assembly Y. As a developer your task is to load the assembly and get the extra information about members, properties, methods and so on. You also want to invoke some methods on an instance of Type employee. In order to achieve the required behavior, ,typeof and GetType() methods may help you in achieving your intended functionality.

typeof keyword takes the Type itself as an argument and returns the underline Type of the argument whereas GetType() can only be invoked on the instance of the type.

typeof

System.Type t1= typeof(Employee); // Employee is a Type

GetType()

Employee employee= new Employee();
System.Type t2= employee.GetType(); // employee is an instance of the type Employee.


Both of examples create an instance of a type class for the Employee type. After you have a reference to the type, you can extract extra information from them as shown below.

  1. Console.WriteLine("AssmeblyQualifiedName: {0}", t1.AssemblyQualifiedName);  
  2. Console.WriteLine("FullName: {0}", t1.FullName);  
  3. Console.WriteLine("IsValueType: {0}", t1.IsValueType);  
  4. Console.WriteLine("Name: {0}", t1.Name);  
  5. Console.WriteLine("Namespace: {0}", t1.Namespace);  
Output:

Output

If you want to execute a method call on an instance, use reflection to load assembly first and retrieve methods info and execute method invocation.