Is Operator in C# with Example
From inheritance, we know that a base class always contains most of the common features and we also know a base class reference variable can point to the derived class object, but vice versa is not possible because a derived class is an extended version of a base class and it contains more functionally than a base class. Due to this reason, we can easily point a derived class object to a base class reference variable using type casting, but vice versa is not possible because there will be a run time error.
using System; namespace Hello { //Employee Class class Employee { public void PrintName() { Console.WriteLine("This is an Employee Class."); } } //Manager Class class Manager:Employee { public new void PrintName() { Console.WriteLine("This is a Manager Class."); } } class Program { static void Main(string[] args) { Manager man = new Manager(); //Type casting Employee emp = (Employee)man; emp.PrintName(); } } }
Output:
This is an Employee Class.
Press any key to continue . . .
There is always is-a relationship between between base class and derived class. For example, consider there is a base class called Employee. You have 2 more classes, called Manager and Supervisor, which are inheriting from Employee base class. By the concept of is-a relationship, Manager is-a Employee and Supervisor is-a Employee. Every Employee cannot be Manager or Supervisor.
While type casting, there are chances that you will encounter run time error and to overcome this issue, we always check for is-relationship. To find this is-a relationship, we use is operator, which returns a boolean value (true or false). Using is operator, you can check whether an underlying class of the object is inheriting from other class or not.
using System; namespace Hello { //Employee Class class Employee { public void PrintName() { Console.WriteLine("This is an Employee Class."); } } //Manager Class class Manager:Employee { public new void PrintName() { Console.WriteLine("This is a Manager Class."); } } class Program { static void Main(string[] args) { Manager man = new Manager(); //This is-a relationship check if(man is Employee) { Employee emp = (Employee)man; emp.PrintName(); } } } }
Output:
This is an Employee Class.
Press any key to continue . . .