Type Checking in C#: typeof, GetType() or is — what and when to use?
Hello everyone. I'm a beginner C# developer and I constantly get confused with type checks. There are three ways: `typeof`, the `GetType()` method, and the `is` operator.
For example, I have this code:
```csharp
object obj = "Hello";
// Option 1
if (obj.GetType() == typeof(string))
Console.WriteLine("This is a string via GetType");
// Option 2
if (obj is string)
Console.WriteLine("This is a string via is");
// Option 3
Type t = typeof(string);
```
It seems like all three check the type, but I notice strange behavior. When I use `is` with nullable types, it behaves differently than `GetType()`. For example:
```csharp
int? x = 5;
if (x is int) // true
Console.WriteLine("x is int");
if (x.GetType() == typeof(int)) // also true
Console.WriteLine("x.GetType == typeof(int)");
```
But if x = null, then `x is int?` returns false, and `GetType()` will throw a NullReferenceException.
Also, I read that `typeof` works only with types at compile time, while `GetType
No answers yet.
Log in to leave an answer
Blogs