As Operator
The as operator is used for conversion between compatible reference types.
For example:
String S = Someobject As String ;
If (S ! = Null )
{
// Someobject is a string.
}
Remarks
The as operator is similar to the forced conversion operation. However, if the conversion fails, as returns NULL instead of triggering an exception. See the following expression:
Expression as type
It is equivalent to the following expression, but only evaluates expression once.
Expression is type? (Type) expression: (type) null
Note that the as operator only performs reference conversion and packing conversion. The as operator cannot perform other conversions, such as user-defined conversions. Such conversions should be executed using forced conversion expressions.
Example
Code
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 [] Bjarray = 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 }
1 0 : Not String
2 1 : Not String
3 2 : ' Hello '
4 3 : Not String
5 4 : Not String
6 5 : Not String
This is another type of conversion.
2010-01-03 20:14:25