I have many code styles specified in my .editorconfig
file for my C# projects. I would find really useful if all of my classes could be sealed
by default (When you create a new one). Is there a setting for this in the .editorconfig
file ?
PS: Please dont explaint if it is/isnt a good idea, there are many such threads on SO, so it would be redundant.
CodePudding user response:
You could edit the visual studio item templates, which it uses when it creates a new file.
I've done this before to change it to default to public classes instead of private(or internal now with visual studio 2022).
This is the location for Community edtion, but the other editions will be similar.
C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class
Note: the files are indifferent places, for ASP.Net core projects for example so you may need to hunt around.
CodePudding user response:
The editor config file doesn't handle creating new classes, in VS it's code snippets and templates that do -- the things you select from that huge nested list of file types. If you want those to generate sealed classes, you have to either edit them or create your own.
Another direction you could go is to write a code analyzer and fix provider that makes your classes sealed
, provided a set of conditions you get to pick and implement are true. This has the added benefit of applying retroactively to your already written code as well.
CodePudding user response:
[not tested] There are also some .editorconfig
preferences, but they just seem to give a suggestion:
[*.cs]
dotnet_diagnostic.MA0053.severity = suggestion
# Report public classes without inheritors (default: false)
MA0053.public_class_should_be_sealed = true
# Report class without inheritors even if there is virtual members (default: false)
MA0053.class_with_virtual_member_shoud_be_sealed = true
Source:
https://www.meziantou.net/performance-benefits-of-sealed-class.htm