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
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.