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.

Type type = typeof (string);<br />

Type[] parameterTypes = { typeof (int) };<br />

MethodInfo method = type.GetMethod ("Substring", parameterTypes);<br />

object[] arguments = { 2 };<br />

object returnValue = method.Invoke ("stamp", arguments);<br />

Console.WriteLine (returnValue); // "amp"<br />

Because the Substring method is overloaded, we had to pass an array of parameter<br />

types to GetMethod to indicate which version we wanted. Without the parameter<br />

types, GetMethod would throw an AmbiguousMatchException.<br />

The GetParameters method, defined on MethodBase (the base class for MethodInfo and<br />

ConstructorInfo), returns parameter metadata. We can continue our previous example<br />

as follows:<br />

ParameterInfo[] paramList = method.GetParameters();<br />

foreach (ParameterInfo x in paramList)<br />

{<br />

Console.WriteLine (x.Name); // startIndex<br />

Console.WriteLine (x.ParameterType); // System.Int32<br />

}<br />

Dealing with ref and out parameters<br />

To pass ref or out parameters, call MakeByRefType on the type before obtaining the<br />

method. For instance, this code:<br />

int x;<br />

bool successfulParse = int.TryParse ("23", out x);<br />

can be dynamically executed as follows:<br />

object[] args = { "23", 0 };<br />

Type[] argTypes = { typeof (string), typeof (int).MakeByRefType() };<br />

MethodInfo tryParse = typeof (int).GetMethod ("TryParse", argTypes);<br />

bool successfulParse = (bool) tryParse.Invoke (null, args);<br />

Console.WriteLine (successfulParse + " " + args[1]); // True 23<br />

This same approach works for both ref and out parameter types.<br />

Retrieving and invoking generic methods<br />

Explicitly specifying parameter types when calling GetMethod can be essential in disambiguating<br />

overloaded methods. However, it’s impossible to specify generic<br />

parameter types. For instance, consider the System.Linq.Enumerable class, which<br />

overloads the Where method as follows:<br />

public static IEnumerable Where<br />

(this IEnumerable source, Func predicate);<br />

public static IEnumerable Where<br />

(this IEnumerable source, Func predicate);<br />

To retrieve a specific overload, we must retrieve all methods and then manually find<br />

the desired overload. The following query retrieves the former overload of Where:<br />

694 | Chapter 18: Reflection and Metadata

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

Saved successfully!

Ooh no, something went wrong!