The IS and as operators of C #

Source: Internet
Author: User
Tags bool empty

In this article I want to summarize my understanding of the IS and as operators to review the C # basics.

Is operator: Checks whether the object is compatible with the given type.

Description

1>: If the supplied expression is not empty, and the provided object can be cast to the supplied type without causing an exception to be thrown, the is expression evaluates to True, otherwise it returns false.

1): null expression: Return False

//表达式为空
object oo = null;
bool isstudent3 = oo is student;

2): expression content is not empty, but an exception occurred while casting the type, return False

oo = new object();
bool isstudent4 = oo is student;

3): When the expression is null, the exception is not thrown because there is no correct object to do type validation.

The 2>:is operator only considers reference conversions, boxing conversions, and unboxing conversions. The following program has a compile-time error (CTE): The known expression will always be true or always false

int i=5;
            if (i is decimal )
            {
                //提示:给定表达式始终不是所提供的("decimal")类型
               }
            if (i is int)
            {
                //给定表达式始终为所提供的("int")类型
               }

3>: The is operator cannot be overloaded.

4>: The first operand of the "is" or "as" operator cannot be a lambda expression or an anonymous expression.

if ((delegate(int i) { return i; }) is testdelegate)
            {
                //提示:"is"或"as"运算符的第一个操作数不能是lambda表达式 或匿名表达式
              }
            if (((x) => { return x; }) is testdelegate)
            {
                //提示:"is"或"as"运算符的第一个操作数不能是lambda表达式或匿名表达式
               }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.