Forcing Extension Methods to Be Used
I received the following question:
Is it possible to force a namespace to be included so that the extension methods in it will be used in it instead of the methods in the main class?
I have to admit, I had to go and do a little research on this, but once I did, I found out that the assumption behind the question is inaccurate.
Rule number one of extension methods is that if an instance method exists on a class, that method will take priority over any extension method that might otherwise be called.
So if you wanted to provide an extension method that converts a number to a string using the ToString() method by creating your own ToString() extension method that acts on an integer to format it some specific way, you will still get the default ToString() method when you call ToString().
Further, if you have two extension methods that could be called and one is in the current namespace and one is in another namespace, the one in the current namespace will be called first.
Finally, if you have two methods in two different namespaces, the normal rules regarding which method will get called come in to play.
So, to answer the original question, no, you can’t force a namespace to be used. And even if you could, it wouldn’t solve your problem.
Other places talking about Extension Methods:
- Generic Extension Method to Unit Test INotifyPropertyChanged
- Two Extension Methods For DevExpress.XtraBars.PopupMenu « M.Efe …
- ‘In’ Operator for .NET Framework
Other Related Items:
Zevia Natural Diet Soda, Cola, 12-Ounce Cans (Pack of 24)ZEVIA Natural Cola has a classic cola taste. It does not contain phosphoric acid (which is usually found in cola flavored beverages, despite research ... Read More >
Hawaiian Host SELECTED WHOLE AND HALVES CHOCOLATE COVERED MACADAMIA NUTS GIFT BOX NET WT 16 OZ (453 g)It truly is Hawaii's Gift to the world!
Selected Macadamias whole and halves covered with Hawaiian Host's special blend of rich and creamy ch... Read More >
Learning C# 3.0If you're new to C#, this popular book is the ideal way to get started. Completely revised for the latest version of the language, Learning C# 3.0 ... Read More >










[...] Forcing Extension Methods to Be Used (Dave M. Bush) [...]
What I do sometimes is to define the extension method in the same namespace as the type I’m extending. For example, if I want to add an extension method to System.Windows.Forms.Control, I can define it within namespace System.Windows.Forms. Then, so long as I have a reference to that assembly, the extension will always be available, and no additional using/import statement will be needed.