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