Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

C# Dictionary

  1. Home
  2. C# Dictionary
  3. is / as / Pattern Matching

is / as / Pattern Matching

The is operator checks an object's type, as safely casts it, and pattern matching (switch expressions and when guards) was enhanced in C# 8 and later.

Syntax

// Checks the type (returns true/false).
bool result = obj is Type;

// Checks the type and assigns to a variable (pattern variable).
if (obj is Type variable) { ... }

// Safe cast — returns null if the cast fails.
Type variable = obj as Type;

// Pattern matching with a switch expression.
string result = value switch {
	Type1 v => ...,
	Type2 v when condition => ...,
	_ => defaultValue
};

Syntax overview

SyntaxDescription
obj is TypeReturns a bool indicating whether obj is the specified type. Returns false for null.
obj is Type vAssigns obj to variable v if the type matches (type pattern variable). Available in C# 7 and later.
obj as TypeAttempts a type conversion. Returns null instead of throwing an exception on failure. Cannot be used with value types.
switch expressionAvailable in C# 8 and later. Each case is written with an arrow (=>) and the expression returns a value.
when guardAdds an extra condition to a switch case.

Sample code

using System;

// Check the type with is.
object value = "Hello";
if (value is string text) {
	Console.WriteLine($"String: {text.ToUpper()}"); // HELLO
}

// Safely cast with as.
object number = 42;
string str = number as string; // No crash even if the cast fails
Console.WriteLine(str == null ? "Cast failed" : str); // Cast failed

// Pattern matching with a switch expression.
object[] items = { 42, "abc", 3.14, true, null };
foreach (object item in items) {
	string description = item switch {
		int n when n > 100 => $"Large integer: {n}",
		int n             => $"Integer: {n}",
		string s          => $"String: {s}",
		double d          => $"Double: {d}",
		bool b            => $"Boolean: {b}",
		null              => "null",
		_                 => "Unknown type"
	};
	Console.WriteLine(description);
}

Notes

Since C# 7, is can perform a type check and variable assignment at the same time, so the old pattern of checking with is and then casting separately is no longer needed. Writing if (obj is string s) on a single line is the modern style.

as can be used for reference type casts, but not for value types such as int or structs. If you use the result without checking for null, a null reference exception will be thrown later. Always perform a null check after using as.

For setting a default value when a result is null, see 'Null-coalescing operators ?? / ??='.

If you find any errors or copyright issues, please .