CHAPTER 11 ADVANCED C# LANGUAGE FEATURES
object to use a brand-new method named DisplayDefiningAssembly() that makes use of types in the
System.Reflection namespace to display the name of the assembly containing the type in question.
Note You will formally examine the reflection API in Chapter 15. If you are new to the topic, simply understand
that reflection allows you to discover the structure of assemblies, types, and type members at runtime.
The second extension method, named ReverseDigits(), allows any int to obtain a new version of
itself where the value is reversed digit by digit. For example, if an integer with the value 1234 called
ReverseDigits(), the integer returned is set to the value 4321. Consider the following class
implementation (be sure to import the System.Reflection namespace if you are following along):
static class MyExtensions
{
// This method allows any object to display the assembly
// it is defined in.
public static void DisplayDefiningAssembly(this object obj)
{
Console.WriteLine("{0} lives here: => {1}\n", obj.GetType().Name,
Assembly.GetAssembly(obj.GetType()).GetName().Name);
}
// This method allows any integer to reverse its digits.
// For example, 56 would return 65.
public static int ReverseDigits(this int i)
{
// Translate int into a string, and then
// get all the characters.
char[] digits = i.ToString().ToCharArray();
// Now reverse items in the array.
Array.Reverse(digits);
// Put back into string.
string newDigits = new string(digits);
// Finally, return the modified string back as an int.
return int.Parse(newDigits);
}
}
Again, note how the first parameter of each extension method has been qualified with the this
keyword, before defining the parameter type. It is always the case that the first parameter of an extension
method represents the type being extended. Given that DisplayDefiningAssembly() has been prototyped
to extend System.Object, every type now has this new member, as Object is the parent to all types in the
.NET platform. However, ReverseDigits() has been prototyped to only extend integer types and,
therefore, if anything other than an integer attempts to invoke this method, you will receive a compiletime error.
419