CSharp examples for Custom Type:as
The as operator performs a downcast that evaluates to null rather than throwing an exception if the downcast fails:
using System; public class Item { public string Name; } public class Stock : Item // inherits from Item { public long SharesOwned; } public class Company : Item // inherits from Item { public decimal Mortgage; } class Test { static void Main(){ Item a = new Item(); Stock s = a as Stock; // s is null; no exception thrown } }
This is useful when you're going to subsequently test whether the result is null:
if (s != null)
Console.WriteLine (s.SharesOwned);