Search code examples
c#visual-studioeditorconfigsealedsealed-class

Make class sealed by default


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.


Solution

  • 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