[Solved] Difference between ‘is’ and ‘==’ in C#


They check completely different things. is compares types. == compares values.

var isString = "Abc" is String; // => true
var equalToString = "Abc" == String; // Error: `string' is a `type' but a `variable' was expected

There is one domain where these can both apply, and have different meanings, and that’s in type checking:

class Car {}
class SportsCar: Car {}

var car = new Car();
var sportsCar = new SportsCar();

/* 1 */ Console.WriteLine(car is Car); // => true, car is exactly of type Car
/* 2 */ Console.WriteLine(sportsCar is Car); // => true, since SportsCar *is a subclass* of Car
/* 3 */ Console.WriteLine(car is SportsCar); // => false, since Car is not a subclass of SportsCar
/* 4 */ Console.WriteLine(sportsCar is SportsCar); // => true, sportsCar is exactly of type SportsCar

/* 5 */ Console.WriteLine(car.GetType() == typeof(Car)); // => true, car is exactly of type Car
/* 6 */ Console.WriteLine(sportsCar.GetType() == typeof(Car)); // => false, since SportsCar *is not exactly* Car
/* 7 */ Console.WriteLine(car.GetType() == typeof(SportsCar)); // => false, since Car is not a subclass of SportsCar
/* 8 */ Console.WriteLine(sportsCar.GetType() == typeof(SportsCar)); // => true, sportsCar is exactly of type SportsCar

Lines 1/5, 3/7, and 4/8 both result the same (respectively) but notice that line 2 and 6 differ

9

solved Difference between ‘is’ and ‘==’ in C#