As, no conversion between abnormal reference types

Source: Internet
Author: User

Converts compatible reference types. For example:

String s = someObject as string;

1if (s! = Null)
2 {
3 // someObject is a string.
4}
5

Remarks
The as operator is similar to forced conversion. The difference is that when the conversion fails, the operator will generate null instead of exception. More strictly speaking, this form of expression 1 expression as type
2

Equivalent to 1 expression is type? (Type) expression: (type) null
2

Example:1 // cs_keyword_as.cs
2 // The as operator.
3 using System;
4 class Class1
5 {
6}
7
8 class Class2
9 {
10}
11
12 class MainClass
13 {
14 static void Main ()
15 {
16 object [] objArray = new object [6];
17 objArray [0] = new Class1 ();
18 objArray [1] = new Class2 ();
19 objArray [2] = "hello ";
20 objArray [3] = 123;
21 objArray [4] = 123.4;
22 objArray [5] = null;
23
24 For (INT I = 0; I <objarray. length; ++ I)
25 {
26 string S = objarray [I] as string;
27 console. Write ("{0}:", I );
28 If (s! = NULL)
29 {
30 console. writeline ("'" + S + "'");
31}
32 else
33 {
34 console. writeline ("not a string ");
35}
36}
37}
38}
39

Output:10: Not a string
21: Not a string
32: 'hello'
43: Not a string
54: Not a string
65: Not a string
7

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.