С# 12, primary constructors

48 views Asked by At

In new version of C# (v.12) there are primary constructors, so, we can write:

public interface IService
{
    Distance GetDistance();
}

public class ExampleController(IService service) : ControllerBase
{
    private readonly IService _service = service;
    [HttpGet]
    public ActionResult<Distance> Get()
    {
        return _service.GetDistance();
    }
}

or even this

public class ExampleController(IService service) : ControllerBase
{
    [HttpGet]
    public ActionResult<Distance> Get()
    {
        return service.GetDistance();
    }
}

second option even more comfortable to use (and shorter) But, is it good way (option #1) or possible is better to use option #1? Because theoretically, we can change service variable with unexpected behavior directly in the code.

0

There are 0 answers