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 { } } }