C# – Using the is operator

You can use the is operator to check if an object is a certain type. Here’s an example:

Person person = new Employee()
{
	Name = "Julius Caesar",
	Position = "Senior .NET Dev"
};

if (person is Employee)
{
	Console.WriteLine($"We're dealing with an employee here");
}
Code language: C# (cs)

You can also use the is operator to declare a variable of the target type, like this:

Person person = new Employee()
{
	Name = "Julius Caesar",
	Position = "Senior .NET Dev"
};

if (person is Employee employee)
{
	Console.WriteLine($"We're dealing with {employee.Name} - {employee.Position} here");
}
Code language: C# (cs)

Note: The employee object is only available in the if block, but IntelliSense shows it out of its scope. If you try to use it out of its scope, you’ll see an error: “Use of unassigned variable.”

Avoid InvalidCastException with the is operator

When an object can’t be explicitly casted to a type, it throws an InvalidCastException. Use the is operator to avoid this problem. The is operator returns false if the object can’t be casted. Here’s an example:

object animal = new Dog()
{
	Name = "Caesar"
};

if (animal is Person)
{
	Console.WriteLine("Animal is a person");
}
else
{
	Console.WriteLine("This animal isn't a person!");
}
Code language: C# (cs)

This outputs:

This animal isn't a person!Code language: plaintext (plaintext)

Nulls and the is operator

The is operator returns null if the object is null. Here’s an example:

Employee employee = null;

if (employee is Employee)
{
	Console.WriteLine("It's an employee");
}
else
{
	Console.WriteLine("It's not an employee, or it was null");
}Code language: JavaScript (javascript)

This outputs:

It's not an employee, or it was nullCode language: plaintext (plaintext)

Using the is operator’s declared variable

You can use the is operator’s declared variable to check more conditions about the variable. Here’s an example:

Person person = new Employee()
{
	Name = "Julius Caesar",
	Position = "Senior .NET Dev"
};

if (person is Employee employee && employee.Name == "Julius Caesar")
{
	Console.WriteLine($"All hail {employee.Position} Caesar!");
}
Code language: C# (cs)

If the person object is an Employee, then employee.name is checked too.

This outputs:

All hail Senior .NET Dev Caesar!Code language: plaintext (plaintext)

Without this, you’d have to check this employee.name in a nested if block.

Leave a Comment