Skip to content

Weird behavior in files with top-level statements #4068

@bjornhellander

Description

@bjornhellander

Created this from PR comment #4054 (comment).

Consider a console app with this code in Program.cs:

// <copyright file="Program.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>

/// <summary>
/// Program.
/// </summary>
internal static class Program
{
    /// <summary>
    /// Program entry point.
    /// </summary>
    public static void Main()
    {
        var x = new MyData();
        //// Do something more here
    }

    private class MyData
    {
    }
}

This triggers no StyleCop diagnostics.

If I simplify this to use top-level statements, I get this:

// <copyright file="Program.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>

var x = new MyData();
//// Do something more here

/// <summary>
/// Contains some data.
/// </summary>
internal class MyData
{
}

Note that the compiler forces me to change MyData to no longer be private.

This triggers SA1649 (File name should match first type name) which wants the file name to be MyData.cs. Program.cs is still the natural name in my opinion, since the primary responsibility for this file is to define the entry point code. The desired action would in my opinion be to move MyData to a separate file.

I suggest that SA1649 should be changed to allow any file name when containing top-level statements and also to update SA1642 (File may only contain a single type) to also trigger on the first type in files with top-level statements. Otherwise, the diagnostic and available code fix might push users to rename the file instead, which I think is the wrong thing to do.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions