C# Is Cast Example

Is cast operator

The is operator returns true if the cast succeeds. It returns false if the cast fails. With it, you cannot capture the casted variable—it is always discarded. This operator is most useful in your C# programs when checking types in if-statements and expressions.

Keywords

Note: The is-cast is only ideal if the casted variable will not be needed for further use. If you need to use the casted variable, use the as-cast.

Example

Note

To start off with, this example demonstrates how the 'is' operator is used in if-statement expressions. Like any operator, the is operator is used to create an expression. It returns a boolean result of true or false. This is perfectly compatible with the if-statement, which requires a boolean context. This example shows how the is operator evaluates the entire class derivation chain when it is applied: the string is both an object and string.

Program that uses is operator to cast [C#]

using System;
using System.Text;

class Program
{
    static void Main()
    {
	// Create a string variable and cast it to an object.
	string value1 = "Example";
	object value2 = value1;

	// Apply the is operator with three different parameters.
	if (value2 is object)
	{
	    Console.WriteLine("is object");
	}
	if (value2 is string)
	{
	    Console.WriteLine("is string");
	}
	if (value2 is StringBuilder)
	{
	    Console.WriteLine("is StringBuilder"); // Not reached
	}
    }
}

Output

is object
is string

Three is casts used. The example shows three different is casts being performed in the if-statement expressions. The first two if-statement bodies are reached; their expressions are evaluated to the true value. The third if-statement body is not fully evaluated because the string is not a StringBuilder type.

Instructions

.NET Framework information

At the level of the intermediate language, the is operator cast is implemented with the isinst instruction. This instruction checks the very top of the evaluation stack and compares the type of that variable to the argument type.

Intermediate Language

Performance

Performance optimization

Often, you may need to actually use in some way a casted value. The is cast only functions as a test, as it returns a boolean only. To store the value received by a cast in a local variable, please use the as operator cast, which returns null if the cast does not succeed. The FxCop static analysis tool provides tips on this.

As Cast Example FxCop Performance Warnings

Summary

The C# programming language

We looked at a brief example of the 'is' operator casting expression in the C# programming language. While there are other ways to cast types in the language, the is operator is exception-neutral and can be elegantly used in an if-statement expression, as it is evaluated to a boolean value. Finally, we examined the instruction-level code in short and pointed to the as cast.

Cast Examples
.NET