Introduction:
"as" operator keyword is used to perform conversions between reference/nullable/boxing types.
Syntax:
[ expression as type ]
where expression = expression of type (objName)
type = reference type
string value = refObject as string;
if ( refObject != null)
{
// refObject is of string type.
}
Example:
namespace DotNetMirror
{
class asOperatorKeyword
{
static void Main()
{
Mirror objM = new Mirror();
Console.WriteLine("objM = {0}", objM == null ? "null" : objM.ToString());
ConvexMirror objCM = new ConvexMirror();
Console.WriteLine("objCM = {0}", objCM == null ? "null" : objCM.ToString());
ConvexMirror objMasCM = objM as ConvexMirror;
Console.WriteLine("objMasCM = {0}", objMasCM == null ? "null" : objMasCM.ToString());
//as like Cast
object obj = new Mirror();
string objasString = obj as string;
Console.WriteLine("objasString = {0}", objasString == null ? "null" : objasString);
Console.ReadLine();
}
}
class Mirror
{
}
class ConvexMirror : Mirror
{
}
}
Output:
"as" like Cast:
as operator is same like cast except that it returns null on conversion failure instead of throwing an exception.
{ expression as type } = { expression is type ? (type)expression : (type) null }
object obj = new Mirror();
string str = obj as string;
Console.WriteLine("obj = {0}", str == null ? "null" : objCM.ToString());
If observe above code obj is of type Mirror, but we performed conversion to string using "as" keyword. Object obj is not of type string so it returns null and prints null.
as with Nullable Types:
int? i = null;
Console.WriteLine("i = {0}", i as int? == null ? "null" : i.ToString());
Note : "as" operator performs only reference/nullable/boxing conversions and it can't perform other conversions like user-defined conversions. In order perform other conversions use cast expressions.