Advertisement
Guest User

Untitled

a guest
Oct 19th, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.82 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. namespace Is
  5. {
  6. class Program
  7. {
  8. static void Main(string[] args)
  9. {
  10. //List of objects that we will check the type of.
  11. List<object> list = getList();
  12.  
  13. //Counters.
  14. int myClassCount = 0;
  15. int mySecondClassCount = 0;
  16.  
  17. //We will use the "is" operator to check if a variable is of a certain type.
  18. foreach (var item in list)
  19. {
  20. //The is operator returns true if the object type matches up and false if it doesn't.
  21. if (item is MyClass)
  22. {
  23. myClassCount++;
  24. }
  25. else if (item is MySecondClass)
  26. {
  27. mySecondClassCount++;
  28. }
  29. }
  30.  
  31. Console.WriteLine("There were " + myClassCount + " instances of MyClass and " + mySecondClassCount + " instances of MySecondClass in this list.");
  32. Console.ReadLine();
  33. }
  34.  
  35. //This method returns a list filled with either MyClass or MySecondClass instances, depending on the random value.
  36. public static List<object> getList()
  37. {
  38. List<object> list = new List<object>();
  39. Random rand = new Random();
  40.  
  41. for (int i = 0; i < 10; i++)
  42. {
  43. if (rand.Next(1, 2 + 1) > 1)
  44. {
  45. var classObject = new MyClass();
  46. list.Add(classObject);
  47. }
  48. else
  49. {
  50. var classObject = new MySecondClass();
  51. list.Add(classObject);
  52. }
  53. }
  54. return list;
  55. }
  56.  
  57. class MyClass
  58. {
  59. }
  60.  
  61. class MySecondClass
  62. {
  63. }
  64. }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement