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

Create successful ePaper yourself

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

Base Types and Interfaces<br />

Type exposes a BaseType property:<br />

Type base1 = typeof (System.String).BaseType;<br />

Type base2 = typeof (System.IO.FileStream).BaseType;<br />

Console.WriteLine (base1.Name); // Object<br />

Console.WriteLine (base2.Name); // Stream<br />

The GetInterfaces method returns the interfaces that a type implements:<br />

foreach (Type iType in typeof (Guid).GetInterfaces())<br />

Console.WriteLine (iType.Name);<br />

IFormattable<br />

IComparable<br />

IComparable'1<br />

IEquatable'1<br />

Reflection provides two dynamic equivalents to C#’s static is operator:<br />

IsInstanceOfType<br />

Accepts a type and instance<br />

IsAssignableFrom<br />

Accepts two types<br />

Here’s an example of the first:<br />

object obj = Guid.NewGuid();<br />

Type target = typeof (IFormattable);<br />

bool isTrue = obj is IFormattable; // Static C# operator<br />

bool alsoTrue = target.IsInstanceOfType (obj); // Dynamic equivalent<br />

IsAssignableFrom is more versatile:<br />

Type target = typeof (IComparable), source = typeof (string);<br />

Console.WriteLine (target.IsAssignableFrom (source)); // True<br />

The IsSubclassOf method works on the same principle as IsAssignableFrom, but<br />

excludes interfaces.<br />

Instantiating Types<br />

There are two ways to dynamically instantiate an object from its type:<br />

• Call the static Activator.CreateInstance method<br />

• Call Invoke on a ConstructorInfo object obtained from calling GetConstructor<br />

on a Type (advanced scenarios)<br />

Activator.CreateInstance accepts a Type and optional arguments that get passed to<br />

the constructor:<br />

Reflecting and Activating Types | 685<br />

Reflection

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

Saved successfully!

Ooh no, something went wrong!