The as Operator
The as operator works like a cast, except that if it can’t perform the indicated conversion, it returns null
(a null reference that does not refer to any object) rather than throwing an exception as an unsuccessful
explicit conversion would.
For example, the following code snippet will store a null reference in the variable str (with the resulting
display that “i is not a string”):
object i = 42;
string str = i as string;
if (str == null){
MessageBox.Show("i is not a string", "as demo")
}
else {
MessageBox.Show(str, "as demo");
}
Had the variable i contained string data, such as
object i = "hello";
then the string data “hello” would have been displayed in the message box after the object type i was converted
to the string type str.
|
|
Search Engine Optimization
 
Syndication Viewer
Our Web host:
IX WebHosting
|