as keyword C#
As per MSDN: You can use the as operator to perform certain types of conversions between compatible reference types or nullable types.
Example:
class Program
{
static void Main(string[] args)
{
object Name1 = "Dhruv Sheth";
string Name = Name1 as string;
if (Name != null)
Console.WriteLine("'" + Name + "' is a string.");
else
Console.WriteLine("not a string");
object Name2 = 0;
string strNull = Name2 as string;
if (strNull != null)
Console.WriteLine("'" + strNull + "'");
else
Console.WriteLine("not a string");
Console.ReadKey();
}
}
OUTPUT:
'Dhruv Sheth' is a string.
not a string
NOTE:
1. as operator is similar to casting operation. But If the conversion is fail, as returns null instead of throwing an exception.
2. as operator performs only reference conversions, nullable conversions, and boxing conversions.