C# IS

How 'is' keyword perform in C#?

IS Keyword

In C#, the 'is' keyword is used for type testing. It checks whether an object is compatible with a given type. The syntax for using is is as follows:

if (someObject is SomeType) {
    // Code to be executed if someObject is of type SomeType
} else {
    // Code to be executed if someObject is NOT of type SomeType
}

Here, 'someObject' is the object you want to test, and 'SomeType' is the type you want to check against. If 'someObject' is an instance of 'SomeType' or a derived type, the condition will be true; otherwise, it will be false.

Here's a simple example:

cs Copy Code
object myObject = "This is a String.";

if (myObject is string)
{
    Console.WriteLine("myObject is a string.");
}
else
{
    Console.WriteLine("myObject is NOT a string.");
}
Output:
myObject is a string.

In this example, the output will be "myObject is a string," as 'myObject' is assigned a string value.

Here's another small program using multiple 'if-else' statements and the 'is' keyword to categorize objects based on their types:

cs Copy Code
using System;

class Program
{
    static void Main()
    {
        object[] values = { 42, 3.14, "Hi", true, 'A' };

        foreach (var value in values)
        {
            if (value is int)
            {
                Console.WriteLine($"{value} is an integer.");
            }
            else if (value is double)
            {
                Console.WriteLine($"{value} is a double.");
            }
            else if (value is string)
            {
                Console.WriteLine($"{value} is a string.");
            }
            else if (value is bool)
            {
                Console.WriteLine($"{value} is a boolean.");
            }
            else
            {
                Console.WriteLine($"{value} is of an unrecognized type.");
            }
        }
    }
}
Output:
42 is an integer.
3.14 is a double.
Hi is a string.
True is a boolean.
A is of an unrecognized type.

This example illustrates the use of multiple 'if-else' statements with the 'is' keyword to handle different types of objects.

Remember: Keep in mind that the 'is' keyword also works with user-defined types and interfaces. It's a convenient way to check the type of an object before attempting type-specific operations to avoid runtime errors.

What's Next?

We actively create content for our YouTube channel and consistently upload or share knowledge on the web platform.