Javatpoint Logo
Javatpoint Logo

Is Operator Keyword in C#

In this article, we will discuss the Is operator in C# with its syntax and examples.

What is the Is Operator?

The is operator determines if an object's run-time type is comparable with the specified type. It returns true if the provided object is of the same type; otherwise, it returns false. It also returns False for null items. The 'is' keyword is a strong and versatile construct that is essential for type checking and casting.

Syntax:

It has the following syntax:

Here, the expression will be converted into a type instance. Type is the name of the type to which the expression's result will be transformed. If the expression is not null and the object created by evaluating the expression can be converted to the provided type, the operator is going to return true. If not, it will return false.

Example 1:

Let us take an example to illustrate the Is operator in C#.

Output:

Is a is Employee? : True
Is d is a Employee? : False
Is a is Employee? : False

Example 2:

Let us take another example to illustrate the Is operator in C#.

Output:

True
True
True
True
True
False
False

Advantages of is Operator keyword in C#

Several advantages of the Is operator in C# are as follows:

  • Type checking:

The keyword checks if an object is a specific type at runtime. It enables us to develop code that handles objects dynamically based on their type.

  • Type Casting:

If the check is successful, we can securely cast an object to a specified type when we use it in combination with an assignment.

  • Avoiding Invalid Cast Exceptions:

In order to avoid invalid cast exceptions, use the is keyword to validate the type of the object before casting.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA