using System;
class Program {
static void Main() {
object value = "hello";
Console.WriteLine(value is string);
Console.WriteLine(value is int);
}
}
Output
True
False
How It Works
value is string. The object really holds a string, so the result is True.
value is int. It does not hold an int, so the result is False.
No exception. A failed test just returns false.
Example 2 — Check and Use in One Step
Create a typed variable while testing the type.
C#
using System;
class Program {
static void Main() {
object[] items = { 42, "text", null, 3.5 };
foreach (object item in items) {
if (item is null) {
Console.WriteLine("null");
} else if (item is int n) {
Console.WriteLine($"int {n}");
} else if (item is string s) {
Console.WriteLine($"string of length {s.Length}");
} else {
Console.WriteLine($"other: {item}");
}
}
}
}
Output
int 42
string of length 4
null
other: 3.5
How It Works
is int n. If the test passes, n is ready to use as an int.
is string s. Same idea, with s as a string.
No casting. You do not need (int)item anywhere.
Example 3 — null and Relational Patterns
Use is not null and range patterns for short, readable checks.
C#
using System;
class Program {
static void Main() {
string name = "Sam";
int age = 25;
Console.WriteLine(name is not null);
Console.WriteLine(age is >= 18 and < 65);
Console.WriteLine(age is < 0 or > 120);
}
}
Output
True
True
False
How It Works
is not null. A clear way to say "this value exists."
and. Both conditions must be true. 25 is at least 18 and less than 65.
or. Either condition is enough. 25 is not below 0 and not above 120, so the result is False.
Frequently Asked Questions
It checks whether a value matches a type or pattern and returns true or false.
is returns a bool. as returns the converted object, or null when the conversion fails.
It returns false for a type check, because null has no type. Use is null to test for null.
It is value is string text. The type is checked and the new variable text is created in one step.
Yes. Use and, or, and not, for example age is >= 18 and < 65.