Posted By

bernicestockstill on 03/15/18


Tagged


Versions (?)

Testing for type compatibility


 / Published in: C#
 

The is keyword evaluates type compatibility at runtime. It determines whether an object instance or the result of an expression can be converted to a specified type. It has the syntax where expr is an expression that evaluates to an instance of some type, and type is the name of the type to which the result of expr is to be converted. The is statement is true if expr is non-null and the object that results from evaluating the expression can be converted to type; otherwise, it returns false.+

For example, the following code determines if obj can be cast to an instance of the Person type:if (obj is Person) { // Do something if obj is a Person. }

  1. using System;
  2.  
  3. public class Class1 : IFormatProvider
  4. {
  5. public object GetFormat(Type t)
  6. {
  7. if (t.Equals(this.GetType()))
  8. return this;
  9. return null;
  10. }
  11. }
  12.  
  13. public class Class2 : Class1
  14. {
  15. public int Value { get; set; }
  16. }
  17.  
  18. public class Example
  19. {
  20. public static void Main()
  21. {
  22. var cl1 = new Class1();
  23. Console.WriteLine(cl1 is IFormatProvider);
  24. Console.WriteLine(cl1 is Object);
  25. Console.WriteLine(cl1 is Class1);
  26. Console.WriteLine(cl1 is Class2);
  27. Console.WriteLine();
  28.  
  29. var cl2 = new Class2();
  30. Console.WriteLine(cl2 is IFormatProvider);
  31. Console.WriteLine(cl2 is Class2);
  32. Console.WriteLine(cl2 is Class1);
  33. Console.WriteLine();
  34.  
  35. Class1 cl = cl2;
  36. Console.WriteLine(cl is Class1);
  37. Console.WriteLine(cl is Class2);
  38. }
  39. }
  40. // The example displays the following output:
  41. // True
  42. // True
  43. // True
  44. // False
  45. //
  46. // True
  47. // True
  48. // True
  49. //
  50. // True
  51. // True

Report this snippet  

You need to login to post a comment.