The “as” operator

“as” operator is used to cast some parent type to child type. For example, to cast from object to string, in the following example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication8
{

   

    class Program
    {
        

        static void Main(string[] args)
        {
            object o1 = "Some string";
            object o2 = 5;

            string s1 = o1 as string;
            string s2 = o2 as string;

            int myint = (int)o2;

            Console.WriteLine(s1);
            Console.WriteLine(s2);
            Console.WriteLine(myint);

        }

    }
}

 

Tags:,

Add a Comment

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