Both of these two operators -- is and as - execute at run time.
The is operator
The is operator is used for checking whether the object is compatible or not.
- It returns true if the given object is of the same type, else it returns false.
- It also returns false if the object is null.
- Syntax - The following code checks if object is a SmartPhone or not.
- if(obj is SmartPhone)
The as operator
- This operator is used for conversion between compatible reference types.
- It returns the object if they are compatible, else it returns null.
- Syntax - The following code coverts obj into SmartPhone. It's called typecasting.
- SmartPhone smartPhone = obj as SmartPhone;
- Even this is allowed,
- SmartPhone smartPhone = (SmartPhone)obj;
Let's create a basic UML, then we will implement classes as per the UML, to understand these 2 operators.
- Base class - Phone
- Base Interface - ISmartPhone
- Derived class - SmartPhone implementing an interface ISmartPhone & extending a class Phone
- As per this implementation, we know that every SmartPhone is a Phone as well as ISmartPhone
- But not every phone is a SmartPhone. As in the real world, some phones are just meant for calling & texting.

Let's start coding.
First, Base classes and interfaces:
- public class Phone
- {
- }
- public interface ISmartPhone
- {
- string DisplayObject();
- }
- It has properties such as Name & Price of a smartphone
- Overridden method DisplayObject of ISmartPhone interface
- public class SmartPhone : Phone, ISmartPhone
- {
- public string Name { get; set; }
- public double Price { get; set; }
- public string DisplayObject()
- {
- return "Name: " + Name + "||"
- + " Price: " + Price;
- }
- }


Join the conversation! Your thoughts help the community grow.