What is typeof in C#: Explanation and Usage
typeof is an operator used to get the System.Type object for a given type at compile time. It helps you find out information about a type, like its name or properties, without needing an instance of that type.How It Works
The typeof operator in C# works like a label that points to a type's information. Imagine you have a book, and instead of reading the whole book, you just want to know its title or author. typeof gives you that kind of summary about a type.
It does this at compile time, meaning the type you ask about must be known when you write the code. You don't need to create an object of that type to get this information. This is useful because it lets your program learn about types themselves, not just their values.
Example
This example shows how to use typeof to get the name of a type and check if it is a class.
using System; class Program { static void Main() { Type typeInfo = typeof(string); Console.WriteLine("Type name: " + typeInfo.Name); Console.WriteLine("Is class: " + typeInfo.IsClass); } }
When to Use
Use typeof when you need to get information about a type itself, not an object. For example, you might want to check a type's name, its base class, or attributes before creating an object.
It is also helpful in reflection, where programs inspect and manipulate types at runtime, or when working with generic programming to enforce type constraints.
Key Points
- Compile-time operator:
typeofrequires a known type at compile time. - Returns System.Type: It gives a
Typeobject describing the type. - No instance needed: You don’t need to create an object to use it.
- Useful for reflection: Helps inspect type metadata in your code.
Key Takeaways
typeof gets the Type object for a type known at compile time.