The C# typeof
operator returns Type objects. It is often used as a parameter or as a variable or field. It is part of an expression that acquires the Type pointer.
Some methods, like Enum.Parse
, require a Type object, and typeof
can get us this object. We use the typeof
operator to get more information about a class
.
Here we use typeof
in a simple program. The types the program uses are found in the System
namespace and the System.IO
namespace.
typeof
operator uses reflection to access the metadata descriptions of the types.string
representation of these Type pointers. We assign the result of the typeof
operator to a Type variable or field.ToString
on the Type pointers—this returns a string
representation of the type.using System; using System.IO; class Program { static Type _type = typeof(char); // Store Type as field. static void Main() { Console.WriteLine(_type); // Value type pointer Console.WriteLine(typeof(int)); // Value type Console.WriteLine(typeof(byte)); // Value type Console.WriteLine(typeof(Stream)); // Class type Console.WriteLine(typeof(TextWriter)); // Class type Console.WriteLine(typeof(Array)); // Class type Console.WriteLine(typeof(int[])); // Array reference type } }System.Char System.Int32 System.Byte System.IO.Stream System.IO.TextWriter System.Array System.Int32[]
Enum
exampleSome common uses of the typeof
operator are the Enum
static
methods, the DataTable
class
and similar classes, and the ArrayList
conversion methods.
Enum.Parse
with a typeof
argument. With typeof
, we get a Type and we use this as the first argument.using System; enum AnimalType { Bird } class Program { public static void Main() { string name = "Bird"; // Use Enum.Parse with typeof argument. var result = Enum.Parse(typeof(AnimalType), name); // Test result. if ((AnimalType)result == AnimalType.Bird) { Console.WriteLine("OK"); } } }OK
Typeof is an operator. We assigned the result of typeof
expressions to a Type field or variable. There are many common uses of the typeof
operator in .NET.