15.01.2013 Views

Free-ebooks-library - Bahar Ali Khan

Free-ebooks-library - Bahar Ali Khan

Free-ebooks-library - Bahar Ali Khan

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Obtaining array types<br />

As we just saw, typeof and GetType work with array types. You can also obtain an<br />

array type by calling MakeArrayType on the element type:<br />

Type tSimpleArray = typeof (int).MakeArrayType();<br />

Console.WriteLine (tSimpleArray == typeof (int[])); // True<br />

MakeArray can be passed an integer argument to make multidimensional rectangular<br />

arrays:<br />

Type tCube = typeof (int).MakeArrayType (3); // cube shaped<br />

Console.WriteLine (tCube == typeof (int[,,])); // True<br />

GetElementType does the reverse; it retrieves an array type’s element type:<br />

Type e = typeof (int[]).GetElementType(); // e == typeof (int)<br />

GetArrayRank returns the number of dimensions of a rectangular array:<br />

int rank = typeof (int[,,]).GetArrayRank(); // 3<br />

Obtaining nested types<br />

To retrieve nested types, call GetNestedTypes on the containing type. For example:<br />

foreach (Type t in typeof (System.Environment).GetNestedTypes())<br />

Console.WriteLine (t.FullName);<br />

OUTPUT: System.Environment+SpecialFolder<br />

The one caveat with nested types is that the CLR treats a nested type as having special<br />

“nested” accessibility levels. For example:<br />

Type t = typeof (System.Environment.SpecialFolder);<br />

Console.WriteLine (t.IsPublic); // False<br />

Console.WriteLine (t.IsNestedPublic); // True<br />

Type Names<br />

A type has Namespace, Name, and FullName properties. In most cases, FullName is a<br />

composition of the former two:<br />

Type t = typeof (System.Text.StringBuilder);<br />

Console.WriteLine (t.Namespace); // System.Text<br />

Console.WriteLine (t.Name); // StringBuilder<br />

Console.WriteLine (t.FullName); // System.Text.StringBuilder<br />

There are two exceptions to this rule: nested types and closed generic types.<br />

Type also has a property called AssemblyQualifiedName, which<br />

returns FullName followed by a comma and then the full name<br />

of its assembly. This is the same string that you can pass to<br />

Type.GetType, and it uniquely identifies a type within the default<br />

loading context.<br />

Reflecting and Activating Types | 683<br />

Reflection

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

Saved successfully!

Ooh no, something went wrong!