Pages

as operator in C#

The as operator is like a cast. it only performs the reference conversions and boxing convertions, the conversion of user defined is not possible, which has to done by casting explicitly. usage of 'as' operator never raises a exception instead it yields null on conversion failure.

Internally it is equivalent to
expression is type ? (type)expression : (type)null


consider a example,


object [] myobject = new object[5];
myObjects[0] =
new MyClass2();
myObjects[1] = "hello";
myObjects[2] = 123;
myObjects[3] = 123.4;
myObjects[4] = null;
......
for (int i=0;
i<myObjects.Length; ++i)
{

string s = myObjects[i] as string;
Console.Write ("{0}:", i);
if (s != null)
Console.WriteLine ( "'" + s + "'" );
else

Console.WriteLine ( "not a string" );
}


output


0:not a string
1:'hello'
2:not a string
3:not a string
4:not a string

No comments:

Post a Comment