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





