C# Keywords Tutorial Part 49: is

C# Keywords Tutorial Part 49: is

C# is a popular object-oriented programming language with many useful features that make it a go-to choice for developing modern applications. One such feature is the “is” keyword, which allows developers to check if an object is of a particular type.

In this blog post, we will explore the “is” keyword in C# and how it can be used in various scenarios.

The “is” keyword is used to check whether an object is of a specific type. It returns a Boolean value indicating whether the object is of the specified type. Here’s an example of how the “is” keyword can be used:

Object obj = new Object();
if (obj is String)
{
    Console.WriteLine("Object is a String");
}
else
{
    Console.WriteLine("Object is not a String");
}

In this example, we create a new Object and assign it to a variable named “obj”. We then use the “is” keyword to check if the “obj” variable is of type String. Since “obj” is an Object and not a String, the “else” block will be executed and “Object is not a String” will be printed to the console.

The “is” keyword can also be used in conjunction with the “as” keyword, which performs a cast if the object is of the specified type. Here’s an example:

Object obj = "This is a string";
String str = obj as String;
if (str != null)
{
    Console.WriteLine(str);
}
else
{
    Console.WriteLine("Object is not a String");
}

In this example, we create a new Object that contains a string and assign it to the “obj” variable. We then use the “as” keyword to attempt to cast the “obj” variable to a String. If the cast is successful, the “if” block will be executed, and the string value will be printed to the console. If the cast fails, the “else” block will be executed, and “Object is not a String” will be printed.

Another use case for the “is” keyword is in switch statements. The “is” keyword can be used to test if an object is of a particular type in a case statement. Here’s an example:

Object obj = new Object();
switch (obj)
{
    case String str:
        Console.WriteLine("Object is a String");
        break;
    case Int32 i:
        Console.WriteLine("Object is an Int32");
        break;
    default:
        Console.WriteLine("Object is of an unknown type");
        break;
}

In this example, we create a new Object and assign it to the “obj” variable. We then use the “is” keyword in a switch statement to test if the “obj” variable is of type String or Int32. If the “obj” variable is of type String, the “case String str” block will be executed and “Object is a String” will be printed to the console. If the “obj” variable is of type Int32, the “case Int32 i” block will be executed, and “Object is an Int32” will be printed to the console. If the “obj” variable is of any other type, the “default” block will be executed, and “Object is of an unknown type” will be printed.

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *