Best practices: C# Extension methods namespace and promoting extension methods

后端 未结 10 1013
南方客
南方客 2021-02-02 06:43

I know there exists already a post, describing nearly the same, but I think mine is a bit different.

What I would like to know is how you organize your extension methods

相关标签:
10条回答
  • 2021-02-02 07:03

    Yes,i think put the Extension methods in own company namespce is best practices. put it in System namespace is a lazy operation

    0 讨论(0)
  • 2021-02-02 07:10

    @Juri- If you think about it this is the same problem as developers knowing that class X exists in the .NET framework. Communication is key that all team members use the right classes, be they extension methods or some other helper.

    As JP has stated, I often see extension methods in some kind of subfolder called Extensions. Hopefully when you state you use my.company.web.utils the namespace is actually Pascal cased?

    Even if you put them in a good place there is no 100% guarantee that other developers will use them.

    0 讨论(0)
  • 2021-02-02 07:12

    You can achieve what you want by putting extension methods in the global namespace. That's what I do and they're then available without needing any using statements.

    0 讨论(0)
  • 2021-02-02 07:16

    We put them all in their own namespace Company.Common.Extensions. That way, if you have any of our extension methods, you have them all. Plus, at least at my shop, we don't have to worry about our developers not knowing about extension methods. I have the opposite worry, extension method overload! :)

    0 讨论(0)
  • 2021-02-02 07:18

    This is not a namespace problem it is a communication problem.

    If these methods are useful you need to communicate this to the developers and, conversely, act on the feedback from them (with appropriate levels of judgement).

    Placing anything into the System namespace is a recipe for disaster and confusion later. The only times you ever want to do this is to 'back port' functionality into older frameworks and then you probably shouldn't do it yourself but should use something like LinqBridge to do it.

    Be wary of the desire to throw all extensions into one namespace unless they really are widely useful together. Some developers may find the wood lost for the trees if they are bombarded with everything and the kitchen sink via intellisense.

    Keeping the namespace the company name is sensible in general to avoid confusion.

    0 讨论(0)
  • 2021-02-02 07:18

    Presuming you use Visual Studio, one way would be to create a custom Class template (or modify the default one) so that whenever a developer creates a new class file it automatically has a using statement with your namespace(s). See Customize Visual Studio 2005 Templates for Coding Productivity.

    0 讨论(0)
提交回复
热议问题