Forcing Extension Methods to Be Used

tobj-067 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:


Other Related Items:

Skinceuticals  Hydrating B5 Moisture-Enhancing Gel, 1-Ounce BottleSkinceuticals Hydrating B5 Moisture-Enhancing Gel, 1-Ounce BottleEnriched with vitamin B5, known to help with tissue repair, Hydrating B5 Gel replenishes nutrients the skin needs to feel smooth and appear younger.Th... Read More >
Microsoft Visual Studio Professional 2005 [OLD VERSION]Microsoft Visual Studio Professional 2005 [OLD VERSION]Visual Studio 2005 Professional Edition offers developers exactly what they need: A high productivity professional development environment for working... Read More >
Officially Licensed by MLB - New York Yankees Dog Baseball Jersey - MediumOfficially Licensed by MLB - New York Yankees Dog Baseball Jersey - MediumYour dog will look great supporting his/her favorite baseball team - the New York Yankees. Medium fits nape of neck to base of tail 16" - 20"; Girth 16" - 19"; Neck 10" - 14".

Related Post

2 Responses to “Forcing Extension Methods to Be Used”

DotNetNuke Sponsor

 

Most Valuable Blogger
Sponsor