code_junkie

How to use the “is” operator in System.Type variables?

Nov 10th, 2011
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. object ReturnMatch(System.Type type)
  2. {
  3. foreach(object obj in myObjects)
  4. {
  5. if (obj == type)
  6. {
  7. return obj;
  8. }
  9. }
  10. }
  11.  
  12. if (obj is type) // won't compile in C# 2.0
  13.  
  14. if (obj.GetType().Equals(type) || obj.GetType().IsSubclassOf(type))
  15.  
  16. Type theTypeWeWant; // From argument or whatever
  17. foreach (object o in myCollection)
  18. {
  19. if (theTypeWeWant.IsAssignableFrom(o.GetType))
  20. return o;
  21. }
  22.  
  23. private T FindObjectOfType<T>() where T: class
  24. {
  25. foreach(object o in myCollection)
  26. {
  27. if (o is T)
  28. return (T) o;
  29. }
  30. return null;
  31. }
  32.  
  33. if(obj is type)
  34.  
  35. foreach(object obj in myObjects)
  36. {
  37. if (obj is type)
  38. {
  39. return obj;
  40. }
  41. }
  42.  
  43. class Level1
  44. {
  45. }
  46.  
  47. class Level2A : Level1
  48. {
  49. }
  50.  
  51. class Level2B : Level1
  52. {
  53. }
  54.  
  55. class Level3A2A : Level2A
  56. {
  57. }
  58.  
  59.  
  60. class Program
  61. {
  62. static void Main(string[] args)
  63. {
  64. object[] objects = new object[] {"testing", new Level1(), new Level2A(), new Level2B(), new Level3A2A(), new object() };
  65.  
  66.  
  67. ReturnMatch(typeof(Level1), objects);
  68. Console.ReadLine();
  69. }
  70.  
  71.  
  72. static void ReturnMatch(Type arbitraryType, object[] objects)
  73. {
  74. foreach (object obj in objects)
  75. {
  76. Type objType = obj.GetType();
  77.  
  78. Console.Write(arbitraryType.ToString() + " is ");
  79.  
  80. if (!arbitraryType.IsAssignableFrom(objType))
  81. Console.Write("not ");
  82.  
  83. Console.WriteLine("assignable from " + objType.ToString());
  84.  
  85. }
  86. }
  87. }
Add Comment
Please, Sign In to add comment