Partager via


is (C# Reference) 

Checks if an object is compatible with a given type. For example, it can be determined if an object is compatible with the string type like this:

if (obj is string)
{
}

Remarks

An is expression evaluates to true if the provided expression is non-null, and the provided object can be cast to the provided type without causing an exception to be thrown. For more information, see 7.6.6 Cast expressions.

The is keyword results in a compile-time warning if the expression is known to always be true or to always be false, but typically evaluates type compatibility at run time.

The is operator cannot be overloaded.

Note that the is operator only considers reference conversions, boxing conversions, and unboxing conversions. Other conversions, such as user-defined conversions, are not considered.

Example

// cs_keyword_is.cs
// The is operator.
using System;
class Class1
{
}
class Class2
{
}

class IsTest
{
    static void Test(object o)
    {
        Class1 a;
        Class2 b;

        if (o is Class1)
        {
            Console.WriteLine("o is Class1");
            a = (Class1)o;
            // Do something with "a."
        }
        else if (o is Class2)
        {
            Console.WriteLine("o is Class2");
            b = (Class2)o;
            // Do something with "b."
        }
        else
        {
            Console.WriteLine("o is neither Class1 nor Class2.");
        }
    }
    static void Main()
    {
        Class1 c1 = new Class1();
        Class2 c2 = new Class2();
        Test(c1);
        Test(c2);
        Test("a string");
    }
}

Output

o is Class1
o is Class2
o is neither Class1 nor Class2.

C# Language Specification

For more information, see the following sections in the C# Language Specification:

  • 7.9.9 The is operator

See Also

Reference

C# Keywords
typeof (C# Reference)
as (C# Reference)
Operator Keywords (C# Reference)

Concepts

C# Programming Guide

Other Resources

C# Reference