15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Using reflection ❘ 343<br />

need is defined. The code for TypeView is as follows. To begin, you need to add a few using<br />

statements:<br />

using System;<br />

using System.Reflection;<br />

using System.Text;<br />

using System.Windows.Forms;<br />

You need System.Text because you will be using a StringBuilder object to build up the text to be<br />

displayed in the message box, <strong>and</strong> System.Windows.Forms for the message box itself. The entire code<br />

is in one class, MainClass, which has a couple of static methods <strong>and</strong> one static field, a StringBuilder<br />

instance called OutputText, which will be used to build up the text to be displayed in the message box.<br />

The main method <strong>and</strong> class declaration look like this:<br />

class MainClass<br />

{<br />

static StringBuilder OutputText = new StringBuilder();<br />

static void Main()<br />

{<br />

// modify this line to retrieve details of any<br />

// other data type<br />

Type t = typeof(double);<br />

}<br />

AnalyzeType(t);<br />

MessageBox.Show(OutputText.ToString(), "Analysis of type "<br />

+ t.Name);<br />

Console.ReadLine();<br />

The Main() method implementation starts by declaring a Type object to represent your chosen data type.<br />

You then call a method, AnalyzeType(), which extracts the information from the Type object <strong>and</strong> uses it to<br />

build up the output text. Finally, you show the output in a message box. Using the MessageBox class is fairly<br />

intuitive. You just call its static Show() method, passing it two strings, which will, respectively, be the<br />

text in the box <strong>and</strong> the caption. AnalyzeType() is where the bulk of the work is done:<br />

static void AnalyzeType(Type t)<br />

{<br />

AddToOutput("Type Name: " + t.Name);<br />

AddToOutput("Full Name: " + t.FullName);<br />

AddToOutput("Namespace: " + t.Namespace);<br />

Type tBase = t.BaseType;<br />

if (tBase != null)<br />

{<br />

AddToOutput("Base Type:" + tBase.Name);<br />

}<br />

Type tUnderlyingSystem = t.UnderlyingSystemType;<br />

if (tUnderlyingSystem != null)<br />

{<br />

AddToOutput("UnderlyingSystem Type:" + tUnderlyingSystem.Name);<br />

}<br />

AddToOutput("\nPUBLIC MEMBERS:");<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!