Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the best practices for using Extension Methods in .Net?

Tags:

.net

I have seen these being used every which way, and have been accused of using them the wrong way (though in that case, I was using them that way to demonstrate a point).

So, what do you think are the best practices for employing Extension Methods?

Should development teams create a library of extension methods and deploy them across various projects?

Should there be a collection of common extension methods in the form of an open source project?

Update: have decided to create an organization wide extension methods library

like image 788
Vaibhav Avatar asked Aug 06 '08 07:08

Vaibhav


1 Answers

The upcoming release of the Framework Design Guidelines, 2nd Edition will have some guidance for implementing extension methods, but in general:

You should only define extension methods "where they make semantic sense" and are providing helper functionality relevant to every implementation.

You also should avoid extending System.Object as not all .NET languages will be able to call the extension method as an extension. (VB.NET for instance would need to call it as a regular static method on the static extension class.)

Don't define an extension method in the same namespace as the extended type unless you're extending an interface.

Don't define an extension method with the same signature as a "real" method since it will never be called.

like image 95
Scott Dorman Avatar answered Oct 02 '22 02:10

Scott Dorman