In C#, typeof
, GetType()
, and the is
keyword serve distinct purposes for type checking and type retrieval. Here’s when and how to use each:
1. is
Operator (Type Compatibility Check)
- Purpose: Checks if an object is compatible with a type (including inheritance hierarchy).
- Usage:
if (obj is MyClass) { ... } // Includes derived types
if (obj is int) { ... } // Works with value types (boxing handled)
- Key Points:
- Returns
true
for base classes or interfaces if the object implements them. - Handles
null
safely (returnsfalse
ifobj
isnull
). - Use for polymorphic checks (e.g., interface/abstract class validation).
2. GetType()
(Exact Runtime Type)
- Purpose: Retrieves the exact runtime type of an object.
- Usage:
Type type = obj.GetType();
if (type == typeof(MyClass)) { ... } // Exact type match
- Key Points:
- Returns the actual type (ignores inheritance).
- Throws
NullReferenceException
ifobj
isnull
. - Use for exact type checks (e.g., reflection, serialization).
3. typeof
Operator (Type Metadata)
- Purpose: Retrieves the
System.Type
metadata for a compile-time known type. - Usage:
Type type = typeof(MyClass); // Compile-time resolution
- Key Points:
- Operates on type names (not variables).
- Use for reflection, attribute checks, or comparing against
GetType()
.
Comparison Table
Feature | is | GetType() | typeof |
---|---|---|---|
Checks Inheritance | Yes ✅ | No ❌ | N/A |
Handles null | Yes ✅ | No ❌ (throws) | N/A |
Works with Types | Yes (runtime check) | No (instance method) | Yes (compile-time type) |
Performance | Fast (compiler-optimized) | Slightly slower | Compile-time resolution |
When to Use Which?
- Polymorphic Checks:
if (animal is Dog) { ... } // Check if `animal` is a Dog or subclass.
- Exact Type Matching:
if (obj.GetType() == typeof(Dog)) { ... } // Only true for Dog, not subclasses.
- Reflection/Attributes:
var methods = typeof(MyClass).GetMethods(); // Get metadata for MyClass.
Example Workflow
object obj = new GoldenRetriever(); // GoldenRetriever inherits from Dog
// Check compatibility (inheritance-aware)
if (obj is Dog) { ... } // ✅ True
// Check exact type
if (obj.GetType() == typeof(Dog)) { ... } // ❌ False (actual type is GoldenRetriever)
// Get Type metadata
Type dogType = typeof(Dog);
Summary:
- Use
is
for polymorphic or interface-based checks. - Use
GetType()
for exact runtime type comparisons. - Use
typeof
to retrieve compile-time type metadata.