ตัวดำเนินการ as ทำการแปลงชนิดระหว่างชนิดที่เข้ากันได้ คล้าย cast แต่ทำได้เฉพาะ reference conversions, nullable conversions, และ boxing conversions ไม่ทำ user-defined conversions (ใช้ cast แทน)
ตัวอย่าง
string s = obj[i] as string;
ตัวอย่างโค้ด
using System;
public class Demo {
public static void Main() {
object[] obj = new object[2];
obj[0] = "jack"; obj[1] = 32;
for (int i = 0; i < obj.Length; ++i) {
string s = obj[i] as string;
Console.Write("{0}: ", i);
if (s != null) Console.WriteLine("'" + s + "'");
else Console.WriteLine("This is not a string!");
}
Console.ReadKey();
}
}
ผลลัพธ์
0: 'jack' 1: This is not a string!