Type Checking en C#: typeof, GetType() o is — qué y cuándo usar
Hola a todos. Soy un desarrollador C# principiante y siempre me confundo con las comprobaciones de tipos. Hay tres formas: `typeof`, el método `GetType()` y el operador `is`.
Por ejemplo, tengo este código:
```csharp
object obj = "Hello";
// Opción 1
if (obj.GetType() == typeof(string))
Console.WriteLine("Esto es un string mediante GetType");
// Opción 2
if (obj is string)
Console.WriteLine("Esto es un string mediante is");
// Opción 3
Type t = typeof(string);
```
Aparentemente los tres comprueban el tipo, pero noto un comportamiento extraño. Cuando uso `is` con tipos nullable, se comporta de manera diferente a `GetType()`. Por ejemplo:
```csharp
int? x = 5;
if (x is int) // true
Console.WriteLine("x is int");
if (x.GetType() == typeof(int)) // también true
Console.WriteLine("x.GetType == typeof(int)");
```
Pero si x = null, entonces `x is int?` devuelve false, y `GetType()` lanzará una NullReferenceException.
Y otro punto: he leído que `typeof` solo funciona con tipos en tiempo de compilación, mientras que `GetType`...