All types inherit the GetType method from the Object base class. This method returns a Type reference representing the type of the object. The runtime maintains a single instance of Type for each type loaded and all references for this type refer to this same object. This means that you can compare two type references efficiently. The IsStringReader method shown here demonstrates how to test if an object is a System.IO.StringReader.
// Create a new StringReader for testing. Object someObject = new StringReader("This is a StringReader"); // Test if someObject is a StringReader by obtaining and // comparing a Type reference using the typeof operator. if (typeof(System.IO.StringReader) == someObject.GetType())
{ // Do something }
C# provides the is operator as a quick way to perform the same test as the IsStringReader method. In addition, is will return true if the tested object is derived from the specified class. This code fragment tests if someObject is an instance of System.IO.TextReader, or a derived class (such as StringReader).
// Test if someObject is, or is derived from, a TextReader // using the is operator. if (someObject is System.IO.TextReader)
{ // Do something }
Both of these approaches require that the type used with the typeof and is operators be known and resolvable at compile time. A more flexible (but slower) alternative is to use the Type.GetType method to return a Type reference for a named type. The Type reference isn't resolved until run time, which causes the performance hit, but allows you to change the type comparison at run time based on the value of a string. The IsType method here returns true if an object is of a named type and uses the Type.IsSubclassOf method to test if the object is a subclass of the named type.
public static bool IsType(object obj, string type) { // Get the named type, use case insensitive search, throw // an exception if the type is not found. Type t = Type.GetType(type, true, true); return t == obj.GetType() || obj.GetType().IsSubclassOf(t); }
Finally, you can use the as operator to perform a safe cast of any object to a specified type. If the object can't be cast to the specified type, the as operator returns null. This allows you to perform safe casts that are easy to verify, but the compared type must be resolvable at run time. Here's an example:
// Use the "as" operator to perform a safe cast. StringReader reader = someObject as System.IO.StringReader; if (reader != null)
{ // Do something with reader }
No comments:
Post a Comment