Excerpt from:  Bill Blogs in C#
.
August 10, 2008

Overload Resolution on Extension Methods

I had a question from a colleague the other day about extension methods.

I'm simplifying a little, but he was looking for a way to ensure that every source file used the same set of extension methods.

There is one way to enforce this, but it does have an effect on your code organization.

Section 7.5.5.2 of the C# language specification describes how the compiler determines which extension methods are in scope, and which extension methods take precedence over others.

This extract is key:

The search for (a candidate extension method) proceeds as follows:

· Starting with the closest enclosing namespace declaration, continuing with each enclosing namespace declaration, and ending with the containing compilation unit, successive attempts are made to find a candidate set of extension methods:

o If the given namespace or compilation unit directly contains non-generic type declarations Ci with eligible extension methods Mj, then the set of those extension methods is the candidate set.

o If namespaces imported by using namespace directives in the given namespace or compilation unit directly contain non-generic type declarations Ci with eligible extension methods Mj, then the set of those extension methods is the candidate set.

That means if you place extension methods in the same namespace as the code from which you call them, those extension methods win. Furthermore, extension methods in an enclosing namespace will be preferred over other namespaces that have been imported.

Therefore, if you place those extension methods that you want to have as part of your global library in the same namespace as your application, or in a parent namespace of that application, you'll be fine.

Note that you still need to import that namespace into each compilation unit, in order to make those methods accessible.

Topic Tags:  , ,

Syndication OptionsRSS (Rich Site Summary) Feed Atom Feed OPML (Outline Processor Language) Feed MYST-ML (MyST Markup Language) Content Feed MS-Office Smart Tag Subscription