Verifying the Underlying Type with the is Operator

Verifying the Underlying Type with the is Operator

Because C# allows casting down the inheritance chain, it is sometimes desirable to determine what the underlying type is before attempting a conversion. Also, checking the type may be necessary for type-specific actions where polymorphism was not implemented. To determine the underlying type, C# provides the is operator (see Listing 6.22).

Listing 6.22. is Operator Determining the Underlying Type

 public static void Save(object data) {     if (data is string)     {         data = Encrypt((string) data);     }         // ... } 

Listing 6.22 encrypts the data if the underlying type is a string. This is significantly different from encrypting, simply because it successfully casts to a string since many types support casting to a string, and yet their underlying type is not a string.

Although this capability is important, you should consider polymorphism prior to using the is operator. Polymorphism enables support for expanding a behavior to other data types without modifying the implementation that defines the behavior. For example, deriving from a common base type and then using that type as the parameter to the Save() method avoids having to check for string explicitly and enables other data types to support encryption during the save by deriving from the same base type.

Essential C# 2.0
Essential C# 2.0
ISBN: 0321150775
EAN: 2147483647
Year: 2007
Pages: 185 © 2008-2017.
If you may any questions please contact us: