Avatar ·

Type Checking in C#: typeof, GetType() or is? When to use what?

Hi everyone! I'm a beginner C# developer and I can't figure out type checking in C#. There are three ways: the `typeof` operator, the `GetType()` method, and the `is` operator. But when should I use which?\n\nHere's an example that confuses me:\n\n```csharp\nobject obj = "Hello, world!";\n\n// Way 1\nif (obj.GetType() == typeof(string))\n Console.WriteLine("This is a string (GetType)");\n\n// Way 2\nif (obj is string)\n Console.WriteLine("This is a string (is)");\n\n// Way 3\nType t = typeof(string);\nif (obj.GetType() == t)\n Console.WriteLine("This is a string (typeof)");\n```\n\nAll three options work, but I feel like they are not interchangeable. For example, I've heard that `typeof` only works with types at compile time, while `GetType()` works at runtime. And `is` is somehow magical —