Example. The is-operator is used to create an expression. It returns a boolean result of true or false. This is compatible with the if-statement, which requires a boolean context.
Info The is-operator evaluates the entire class derivation chain when it is applied. The string is both an object and string.
Here The first 2 if-statement bodies are reached. Their expressions are evaluated to the true value: the casts succeed.
Then The third if-statement body is not fully evaluated. The string is not a StringBuilder type.
using System;
using System.Text;
// Create a string variable and cast it to an object.
string value1 = "Example";
object value2 = value1;
// Apply the is-operator with 3 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.
}is object
is string
Is, pattern matching. Here we see a separate syntax form for the "is" operator. We have an object, and we want to cast it to a string. We use pattern matching for this.
Here The is-cast tests to see if the variable "wrapper" is a string. If it is a string, a string local called temp2 is introduced.
Important This use of the is-cast combines the as-cast with the is-cast. This is probably the best way to cast C# variables.
string temp = "ancient ship";
object wrapper = temp;
// Use pattern matching to cast the object to a variable.// ... Wrapper is an object.// ... Temp2 is a string reference.
if (wrapper is string temp2)
{
System.Console.WriteLine($"STRING = {temp2}, LENGTH = {temp2.Length}");
}STRING = ancient ship, LENGTH = 12
Is, list matching. In newer versions of C#, we can use the is-keyword to perform pattern matching. So we can test the entire contents of a List with an is-statement.
Tip This is not casting, but is instead checking the entire contents of a List. It uses the same "is" operator.
using System;
using System.Collections.Generic;
List<int> values = [100, 200, 900];
// The is-keyword matches this list.
if (values is [100, 200, 900])
{
Console.WriteLine("SAME LIST");
}
// This check evaluates to false.
if (values is [-100, -1000])
{
Console.WriteLine("???");
}SAME LIST
Summary. The is-operator is exception-neutral. It is elegantly used in an if-statement expression—it is evaluated to a boolean value. We examined the instruction-level code.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Sep 21, 2024 (new example).