C# as Operator

C# Code Snippets as operator
Share:

About

In this code snippet, we will learn how to use the as operator in C#.

The as operator is used to cast objects into different types. It is similar to the is operator. They can both be used to check if an object is of a certain type.

If the conversion is successful the converted object gets returned else a null will be returned.

Let’s have a look at the code below to see how to use the as operator.

Code:

using System;
using System.Collections.Generic;

namespace As
{
    class Program
    {
        static void Main(string[] args)
        {
            //List of objects that we will check the type of.
            List<object> list = getList();

            //Counters.
            int myClassCount = 0;
            int mySecondClassCount = 0;

            foreach (var item in list)
            {
                //Item has to be cast to MyClass. But if the item isn't of type MyClass we will get an exception.
                //MyClass myClassCheck = (MyClass)item;

                //To avoid that we should use "as" to perform the cast.
                //The as operator casts the object if the type matches up and returns null if it doesn't.               
                MyClass myClassCheck = item as MyClass;

                if (myClassCheck != null)
                {
                    myClassCount++;
                }

                MySecondClass mySecondClassCheck = item as MySecondClass;

                if (mySecondClassCheck != null)
                {
                    mySecondClassCount++;
                }
            }

            Console.WriteLine("There were " + myClassCount + " instances of MyClass and " + mySecondClassCount + " instances of MySecondClass in this list.");
            Console.ReadLine();
        }

        //This method returns a list filled with either MyClass or MySecondClass instances, depending on the random value. 
        public static List<object> getList()
        {             
            List<object> list = new List<object>();
            Random rand = new Random();

            for (int i = 0; i < 10; i++)
            {
                if (rand.Next(1, 2 + 1) > 1)
                {
                    var classObject = new MyClass();
                    list.Add(classObject);
                }
                else
                {
                    var classObject = new MySecondClass();
                    list.Add(classObject);
                }
            }
            return list;
        }

        class MyClass
        {
        }

        class MySecondClass
        {
        }
    }
}

Resulting output:

Share:

Leave a Reply

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

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger