C# Typeof Operator

Typeof operator

Typeof returns Type objects. You have encountered this operator in a C# program and want to find more information about its usage as a parameter or as a variable or field. The typeof operator is part of an expression that acquires the Type pointer for a class or value type in the C# language.

Keywords

This C# article covers the typeof operator. The example code shows how to get the type of objects.

Example

Note

Let's look at a program written in the C# language that acquires the Type pointer for various types available in the compilation unit. The types the program uses are found in the System namespace and the System.IO namespace.

The typeof operator uses reflection to access the metadata descriptions of the types and the program then displays the string representation of these Type pointers. It also shows how you can assign the result of the typeof operator to a Type variable or field.

Program that uses typeof expressions [C#]

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
    }
}

Output

System.Char
System.Int32
System.Byte
System.IO.Stream
System.IO.TextWriter
System.Array
System.Int32[]
.NET Framework information

Description. This program shows the string representation of the Type pointer that is returned when the typeof(T) expression is evaluated. Whenever the typeof operator is used, the metadata is used and the Type reference is returned. The metadata in .NET is a relational database that contains many tables for types in your C# programs. It is organized into tokens that relate to offsets in related tables.

Type Class

Calling ToString on Type pointers. This program actually calls the ToString method defined on the Type pointers in memory. The default ToString method simply returns a string representation of the type, such as "System.Char". The lowercase types such as "char" and "int" are actually always aliased to the framework types "System.Char" and "System.Int32" in mscorlib.dll.

Uses

Note

Some common uses of the typeof operator are the Enum static methods, the DataTable class and similar classes, the ArrayList conversion methods, and the HttpWorkerRequest methods used in ASP.NET. This site has descriptions of these usages of the typeof operator.

Enum.GetName Enum.Parse Method DataTable Examples Convert ArrayList to Array HttpWorkerRequest

Performance tip

Programming tip

The typeof operator in the C# language actually ends up using a simple and fast form of reflection on the type pointer. Unfortunately, any kind of reflection is usually too slow for optimized code in a critical loop. Fortunately, you can store the results of the typeof expression as a static member on a class. Then, you can use this static Type field wherever you require the Type pointer.

This is most useful in method calls that require a Type object. Note that the .NET Framework has special optimizations when comparing multiple typeof expressions, and this optimization is not useful in that case.

Static type object used [C#]

static Type _type = typeof(Stopwatch);

Loop statements with typeof expression [C#]

Type type = typeof(Stopwatch);
if (type == null)
{
    throw new Exception();
}

Loop statements with Type cached [C#]

Type type = _type;
if (type == null)
{
    throw new Exception();
}

Results of the benchmark

Iterations:             1000000000

Typeof expression used: 2.55 ns
Type object cached:     0.64 ns

Typeof caching result. This experiment used the benchmarking harness also available on Dot Net Perls, and it shows that evaluating the typeof expression on a class in a tight loop required 2.55 nanoseconds each iteration. Copying a cached static Type pointer only required 0.64 nanoseconds.

Benchmark Programs

Note: This shows that using a static Type field can save almost 2 nanoseconds each time it is used. This is only helpful for typeof expressions that are evaluated extremely frequently.

Summary

The C# programming language

We looked at a simple example of the typeof operator in the C# language and saw how you can assign the result of typeof expressions to a Type field or variable. Next we discussed the metadata organization and then looked at common uses of the typeof operator in the .NET Framework. Finally we tested the typeof expression against a static Type cached pointer and found that this is a viable micro-optimization in some contexts.

Reflection
.NET