C# is Operator

C# Code Snippets is operator
Share:

About

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

The is operator is very similar to the as operator. They can both be used to check if an object is of a certain type. Additionally as can be used to perform type casting.

If the object matches the specified data type true gets returned else false will be returned.

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

Code:

using System;
using System.Collections.Generic;

namespace Is
{
    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;

            //We will use the "is" operator to check if a variable is of a certain type. 
            foreach (var item in list)
            {
                //The is operator returns true if the object type matches up and false if it doesn't. 
                if (item is MyClass)
                {
                    myClassCount++;
                }
                else if (item is MySecondClass)
                {
                    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