Testing for Type Compatibility


In the last section you learned how to retrieve an object's Type using either the GetType() function or the typeof construct. If you have two variables and you want to know if they point to the same type you could always get their Type objects and check their Name property. However, GetType() only reports the type of the object and not whether the object is compatible with another type. For example if a class called MotherInLaw is derived from ExtendedFamily , which is derived from Person , which is derived from System.Object then an object of MotherInLaw is compatible with variables of type MotherInLaw , ExtendedFamily , Person (yes, mothers-in-law are persons) and object . What's more, if a variable of type object points to an instance of MotherInLaw , just from looking at the variable it's impossible to tell whether a variable of type Person could point to the same object or not.

To test if an object is compatible with a type:

  • Type if (var is classname) {} where var is the variable that points to the object you wish to test and classname is the name of the class you wish to compare the variable to ( Figure 7.10 ).

    Figure 7.10 The function AdviceFrequency takes any object of type Person as input. That means that you can pass to the function instances of Person, ExtendedFamily or MotherInLaw (since these classes derive from Person). The function then reports the AdviceFrequency based on the type of object that was passed in.
     class Person { } class ExtendedFamily : Person { } class MotherInLaw : ExtendedFamily { } class DecisionMaker {    static public int AdviceFrequency(  Person p1  )    {      if (  p1 is MotherInLaw  )         return 10;      else if (  p1 is ExtendedFamily  )         return 5;      else         return 1;    } } 

graphics/tick.gif Tips

  • You don't have to have the test comparison in the context of an if statement ( Figure 7.11 ).

    Figure 7.11 The is operator isn't limited to if statements. It simply returns true if the object the variable points to is compatible to a certain class, otherwise it returns false.
     Person p1 = new MotherInLaw(); bool returnCall =  p1 is MotherInLaw  ; 
  • Testing for compatibility is normally done before performing a conversion (also called a cast). Check out the section "Converting from One Type to Another (Casting)" for details.




C#
C# & VB.NET Conversion Pocket Reference
ISBN: 0596003196
EAN: 2147483647
Year: 2003
Pages: 198
Authors: Jose Mojica

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net