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;