using the .Net As operator

The as operator is similar to cast, if the conversion isn’t possible null is returned instead of raising an exception.

using System;

namespace CSharpASoperator
{
    class Program
    {
        static void Main(string[] args)
        {
            var objArray = new object[6];

            objArray[0] = new WithFields();
            objArray[1] = new WithProperties();
            objArray[2] = "A String";
            objArray[3] = 123456789;
            objArray[4] = 1234.5678;
            objArray[5] = null;

            foreach (var t in objArray)
            {
                var s = t as string;

                Console.WriteLine(s ?? "not a string: ");
            }

            Console.ReadKey();

        }

        private class WithFields
        {
            private string _name;

        }

        private class WithProperties
        {
            private string Name { get; set; }
        }
    }
}

From: http://msdn.microsoft.com/en-us/library/vstudio/cscsdfbt.aspx

Leave a Reply

Your email address will not be published. Required fields are marked *