As Operator In C#

As Operator in C#

The As operator in C# is used to convert from one type to another. You can use casting to cast one type to another, but if you apply casting on incompatible types, you will get an exception. The advantage of using the As operator is it does not throw an exception. When a type cannot be converted using As operator, it returns a null value. Comparing two types is also a common use for As operator.

The following syntax uses the As operator to convert an item to a string. If an item cannot be converted to a string, it will return a null value.

string stype = item as string;

The following code is a complete example of using As operator. This code tries to convert some class objects to strings and some string and integer values.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AsOperatorSample
{
    public class Animal { }
    public class Vehicle { }
    public class Car : Vehicle { }
    class Program
    {
        static void Main(string[] args)
        {
            Vehicle v = new Vehicle();
            Animal a = new Animal();
            Car c = new Car();
            System.Collections.ArrayList list = new System.Collections.ArrayList();
            list.Add("Hello As");
            list.Add("12345");
            list.Add(v);
            list.Add(a);
            list.Add(c);
            foreach (object item in list)
            {
                // Try to convert item as a string
                string stype = item as string;

                if (stype != null)
                    Console.WriteLine(item.ToString() + " converted successfully.");
                else
                    Console.WriteLine(item.ToString() + " conversion failed.");
            }
            Console.ReadLine();
        }
    }
}

The output looks like the following where you can see string and integer values are converted successfully while class conversion is failed.

output look


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.