Difference between is and as in C #

Source: Internet
Author: User

1. Is checks whether the object is compatible with the given type

@ 1 check whether the object is an instance or inherited from the parent class

If (students is person)

{

... // Code

}

@ 2 is operator only consider packing, unpacking, and reference conversion;

@ 3 anonymous methods are not allowed on the left side of the is Operator (except for lambda expressions)

Ex:

View code

1 int A = 10; 2 object OBJ = A; 3 if (obj is int) 4 {5 console. writeline ("boxing... "); 6} 7 A = 20; 8 console. writeline ("A = {0}", a); 9 console. writeline ("OBJ = {0}", OBJ); 10 11 12 // output result: 13 boxing... 14 A = 2015 OBJ = 10

 

II. The as operator is used to convert compatible types

@ 1 The as operator is similar to type conversion. The difference is that if the as operator fails to be converted, no error is returned, but a null value is returned;

@ 2 The as operator only performs conversion by referencing, earning, and packing. The as operator cannot perform conversion by definition;

View code

 1             object[] obj=new object[5]; 2             obj[0] = new MyClass(); 3             obj[1] = "hello"; 4             obj[2] = 123; 5             obj[3] = null; 6             obj[4] = 'a'; 7             for (int i = 0; i < obj.Length; i++) 8             { 9                 string s = obj[i] as string;10                 if(s!=null)11                 {12                     Console.WriteLine(s);13                 }14                 else15                 {16                     Console.WriteLine("not string ...");17                 }18             }

 

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.