Use Of The TypeOf Operator In C#

Code sample to show use of the typeof operator and Type.GetType() method in C#. In C#, types are inherited from the System.Type. The C# typeof operator get the System.Type of a type. This code sample shows the use case of typeof operator using C#.

In C#, types are inherited from the System.Type. The C# typeof operator gets the System.Type of a type. This code sample shows the use case of typeof operator using C#.
 
Use Of The TypeOf Operator In C#
 
The typeof operator syntax,
  1. System.Type type = typeof(type);     
The following code sample uses the typeof operator to get the type of various types.
  1. Type tp = typeof(int);    
  2. Console.WriteLine($"typeof {tp}");    
  3. Console.WriteLine(typeof(String));    
  4. Console.WriteLine(typeof(Double));   
The GetType() method is used to get the Type of an object or expression at runtime.
  1. // Get type of a variable     
  2. string name = "Mahesh Chand";    
  3. Type namenameType = name.GetType();    
  4. Console.WriteLine(nameType);    
You can also get a type of a class (object), its methods, properties, and other members.
 
The following code snippet returns a type of the Author object. 
  1. // Get a typeof a class    
  2. Console.WriteLine(typeof(Author));    
Complete code sample,
  1. using System;    
  2.     
  3. namespace typeofOperatorSample    
  4. {    
  5.     class Program    
  6.     {    
  7.         static void Main(string[] args)    
  8.         {    
  9.             Type tp = typeof(int);    
  10.             Console.WriteLine($"typeof {tp}");    
  11.             Console.WriteLine(typeof(String));    
  12.             Console.WriteLine(typeof(Double));    
  13.     
  14.             // Get type of a variable     
  15.             string name = "Mahesh Chand";    
  16.             Type namenameType = name.GetType();    
  17.             Console.WriteLine(nameType);    
  18.     
  19.             // Get a typeof a class    
  20.             Console.WriteLine(typeof(Author));    
  21.     
  22.             Console.ReadKey();    
  23.         }    
  24.     }    
  25.     
  26.     public class Author    
  27.     {    
  28.         public Author() { }    
  29.     }    
  30. }   
The output of the above code generates the following output.
 
CSharp typeof