Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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
- {
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement