C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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.
C# program that uses is-operator to cast
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 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.
}
}
}
Output
is object
is string
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.
C# program that uses pattern matching
class Program
{
static void Main()
{
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}");
}
}
}
Output
STRING = ancient ship, LENGTH = 12