Skip to content

Guidance for using primary constructors when "_underscoreCamelCase" syntax is used for private fields? #70419

@vsfeedback

Description

@vsfeedback

This issue has been moved from a ticket on Developer Community.


[severity:It's more difficult to complete my work]
In every place I've worked at, the desired syntax for private fields is "_underscoreWithCamelCase". It's also the suggested convention in the C# coding style docs. For example, the dependency injection example would be written without primary constructor as follows:

public class ExampleController : ControllerBase
{
    private readonly IService _service;

public ExampleController(IService service)
    {
        _service = service;
    }

[HttpGet]
    public ActionResult<Distance> Get()
    {
        return _service. GetDistance();
    }
}

How is this supposed to be written with primary constructors? Should it be like this?

public class ExampleController(IService _service) : ControllerBase

This looks kind of bizarre. Or should we do this?

public class ExampleController(IService service) : ControllerBase
{
    private readonly IService _service = service;

In this case, we still have a private field service that looks like a local variable and is usable anywhere in the type.

It seems like primary constructors were designed only for people who prefer camelCase for local fields and goes against what's defined in the C# coding style conventions.


Original Comments

Feedback Bot on 10/12/2023, 08:02 PM:

(private comment, text removed)


Original Solutions

(no solutions)

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