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. namespace typeofOperatorSample
  3. {
  4. class Program
  5. {
  6. static void Main(string[] args)
  7. {
  8. Type tp = typeof(int);
  9. Console.WriteLine($"typeof {tp}");
  10. Console.WriteLine(typeof(String));
  11. Console.WriteLine(typeof(Double));
  12. // Get type of a variable
  13. string name = "Mahesh Chand";
  14. Type namenameType = name.GetType();
  15. Console.WriteLine(nameType);
  16. // Get a typeof a class
  17. Console.WriteLine(typeof(Author));
  18. Console.ReadKey();
  19. }
  20. }
  21. public class Author
  22. {
  23. public Author() { }
  24. }
  25. }
The output of the above code generates the following output.
CSharp typeof
Next > Here is an article on the Difference between the typeof Operator and GetType() Method.