Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The typeof operator is a unary operator that obtains the System.Type instance representing a specific C# type at compile time. It takes a type name or a type parameter as its operand and returns the CLR metadata associated with that type, without requiring an allocated object instance.
Type typeInfo = typeof(int);

Technical Characteristics

  • Compile-Time Resolution: The C# compiler resolves the typeof expression to a metadata token. During execution, the Common Language Runtime (CLR) translates this token into a System.Type object reference.
  • Operand Restrictions: The operand must be a type name, a generic type parameter, or an unbound generic type. It cannot be a variable, an expression, or an object instance. To obtain type information from an instance at runtime, the Object.GetType() method is used instead.
  • Reference Equality: The CLR guarantees that exactly one System.Type object exists per type per application domain. Consequently, multiple invocations of typeof for the same type will return the exact same object reference in memory.

Syntax Variations

The operator handles various type categories, including primitives, custom objects, generics, and special system types. Standard and Custom Types
Type stringType = typeof(string);
Type customType = typeof(MyClass);
Void Type The operator can evaluate the void keyword, returning the System.Void type. This is strictly used for reflection purposes, as void cannot be instantiated.
Type voidType = typeof(void);
Arrays The operator supports array types, including multi-dimensional and jagged arrays.
Type singleDimArray = typeof(int[]);
Type multiDimArray = typeof(int[,]);
Generic Types typeof can evaluate both bound (constructed) and unbound generic types. For unbound generics, the syntax omits the type arguments but retains the commas to denote the arity (number of type parameters).
// Bound generic type
Type boundList = typeof(List<int>);

// Unbound generic type (Arity 1)
Type unboundList = typeof(List<>);

// Unbound generic type (Arity 2)
Type unboundDict = typeof(Dictionary<,>);
Generic Type Parameters When used within a generic class or method, typeof can evaluate the generic type parameter T. The actual System.Type returned will depend on the closed constructed type provided at runtime.
public class GenericClass<T>
{
    public Type GetParameterType()
    {
        return typeof(T);
    }
}
Master C# with Deep Grasping Methodology!Learn More