Introduction
In C#, as operator is like a cast
operation, which performs only reference conversion, nullable conversion and
boxing conversion. as keyword can not be perform to other conversion such as
user define conversion.
Example
using
System;
namespace
as_keyword_in_c_sharp
{
class
c1
// create class c1
{
}
class
c2
//create another class c2,which
is return type is string
{
public
string show(string
str)
{
return str;
}
}
class
Program
{
static
void Main(string[]
args)
{
c1 obj1 =
new
c1();
//create object of class c1
c2 obj2 =
new
c2();
//create object of class c2
object[]
obj_array = new
object[6];
//create object type array
object a=
123;
//create object type
variable, which is value is int type
object b =
"welcome";
//create object type variable,
which is value is string type
object c =
10.05;
//create object type
variable, which is value is double type
object d =
null;
//create object type variable,
which is value is null type
//store object type
value in object type array
obj_array[0] = obj1;
obj_array[1] = obj2.show("hello");
obj_array[2] = a;
obj_array[3] = b;
obj_array[4] = c;
obj_array[5] = d;
for (int
k = 0; k < obj_array.Length; k++)
{
Console.Write("
{0} : ", k);
// conversion of
object type value to string type through as keyword
string str
= obj_array[k] as
string;
if (str !=
null)
{
Console.WriteLine("'"
+ str + "'");
}
else
{
Console.WriteLine("No
string");
}
}
Console.ReadLine();
}
}
}
Output