GOTCHA 14 Type.GetType() might fail at run-time


GOTCHA #14 Type.GetType() might fail at run-time

Sometimes you need to retrieve the metadata (type information) from a class whose name you know at compile time. If you are going to experience an error in doing this, it is better for it to occur at compile time than at runtime. Consider Example 2-7.

Example 2-7. Failure of Type.GetType()

C# (Typeof)

 using System; namespace TypeOfKnownClass {     class Test     {         [STAThread]         static void Main(string[] args)         {             Type theType = Type.GetType("Test");             Console.WriteLine(theType.FullName);         }     } } 

VB.NET (Typeof)

 Module Test     Sub Main()         Dim theType As Type = Type.GetType("Test")         Console.WriteLine(theType.FullName)     End Sub End Module 

While the code looks simple, executing it results in a NullReferenceException. The reason for the exception is that Type.GetType() does not recognize the type Test. You must pass Type.GetType() the fully qualified name of the type prefixed by its namespace. And even if you write the fully qualified name, what if you misspell the namespace? While you can easily identify and fix this in testing, you may still waste a few minutes in the process. If the type is known at compile time, it is better to get the metadata using an alternate mechanism, shown in Example 2-8.

Example 2-8. Getting the Type metadata

C# (Typeof)

 using System; namespace TypeOfKnownClass {     class Test     {         [STAThread]         static void Main(string[] args)         {             Type theType = typeof(Test);             Console.WriteLine(theType.FullName);         }     } } 

VB.NET (Typeof)

 Module Test     Sub Main()         Dim theType As Type = GetType(Test)         Console.WriteLine(theType.FullName)     End Sub End Module 

When you use typeof() (C#) and GetType() (VB.NET), the compiler automatically resolves the name Test to its fully qualified name. If there is any ambiguity, the compiler alerts you. This saves time and effort by moving the checking to compile time instead of run time.

IN A NUTSHELL

Finding problems at compile time is better than waiting for them to surface at run time. If possible, that is, if the class name is known at compile time, use typeof/GetType instead of the Type.GetType() method.

SEE ALSO

Gotcha #10, "Type.GetType() may not locate all types."



    .NET Gotachas
    .NET Gotachas
    ISBN: N/A
    EAN: N/A
    Year: 2005
    Pages: 126

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