CHAPTER 11 ADVANCED C# LANGUAGE FEATURES
Importing Extension Methods
When you define a class containing extension methods, it will no doubt be defined within a .NET
namespace. If this namespace is different from the namespace using the extension methods, you will
need to make use of the expected C# using keyword. When you do, your code file has access to all
extension methods for the type being extended. This is important to remember, because if you do not
explicitly import the correct namespace, the extension methods are not available for that C# code file.
In effect, although it can appear on the surface that extension methods are global in nature, they are
in fact limited to the namespaces that define them or the namespaces that import them. Thus, if we
wrap the MyExtensions class into a namespace named MyExtensionMethods, as follows:
namespace MyExtensionMethods
{
static class MyExtensions
{
...
}
}
other namespaces in the project would need to explicitly import the MyExtensionMethods namespace to
gain the extension methods defined by our class.
Note It is common practice to not only isolate extension methods into a dedicated .NET namespace, but into a
dedicated class library. In this way, new applications can “opt-in” to extensions by explicitly referencing the
correct library. Chapter 14 will examine the details of building and using custom .NET class libraries.
The IntelliSense of Extension Methods
Given the fact that extension methods are not literally defined on the type being extended, it is certainly
possible to become confused when examining an existing code base. For example, assume you have
imported a namespace that defined some number of extension methods authored by a teammate. As
you are authoring your code, you might create a variable of the extended type, apply the dot operator,
and find dozens of new methods that are not members of the original class definition!
Thankfully, Visual Studio’s IntelliSense mechanism marks all extension methods with a unique,
down-arrow icon (see Figure 11-1).
421