Reputation: 2377
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) or at least they would show warning there class is not sealed. 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.
Upvotes: 4
Views: 3169
Reputation: 2377
There are also some .editorconfig
preferences, but they work only after installing Meziantou.Analyzer Nuget package into your project. After you build your solution these sealed suggestions will show up.
[*.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
[2023] .NET 7 EDIT:
Now .NET 7 allows you to specify this warning in .editorconfig
like:
# Seal internal types
dotnet_diagnostic.CA1852.severity = warning
But it has one requirement, it works only on internal
classes
Source: https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1852
Upvotes: 6
Reputation: 489
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.
Upvotes: 6
Reputation: 67386
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.
Upvotes: 3