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#.
The typeof operator syntax,
- System.Type type = typeof(type);
The following code sample uses the typeof operator to get the type of various types.
- Type tp = typeof(int);
- Console.WriteLine($"typeof {tp}");
- Console.WriteLine(typeof(String));
- Console.WriteLine(typeof(Double));
The GetType() method is used to get the Type of an object or expression at runtime.
-
- string name = "Mahesh Chand";
- Type namenameType = name.GetType();
- 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.
-
- Console.WriteLine(typeof(Author));
Complete code sample,
- using System;
-
- namespace typeofOperatorSample
- {
- class Program
- {
- static void Main(string[] args)
- {
- Type tp = typeof(int);
- Console.WriteLine($"typeof {tp}");
- Console.WriteLine(typeof(String));
- Console.WriteLine(typeof(Double));
-
-
- string name = "Mahesh Chand";
- Type namenameType = name.GetType();
- Console.WriteLine(nameType);
-
-
- Console.WriteLine(typeof(Author));
-
- Console.ReadKey();
- }
- }
-
- public class Author
- {
- public Author() { }
- }
- }
The output of the above code generates the following output.