Why use readonly to instantiate?

2

I have read and relayed this question / answer a few times and I understand the difference between const and readonly . I have also read the documentation , but I still can not understand what the gain is I have when using readonly .

Scenery I have an application developed in Asp .Net MVC and in it there is a service layer, I "start" these services through dependency injection by controller :

private IMyService _myService;
public MeuConstrutor(IMyService myService)
{
    _myService = myService;
}

I see some people using private readonly IMyService _myService; and in one of the latest updates of visual studio (I can not remember which one), he started suggesting that I add readonly in those cases. But as I said, I do not understand the real gain of using it.

private IMyService _myService; vs private readonly IMyService _myService;

  • When to use readonly ?
  • Is there anything I can use using it?
  • Is there anything missing using it?
  • Why use?
  • Why not use it?
asked by anonymous 17.05.2018 / 18:56

1 answer

4

readonly is just an access modifier like all others. It has no magic.

This access modifier applies to the fields created in a class. When using it, the field can only have a value assigned to it in the code that is inside the constructor of the class.

For example, the code below will generate a compilation error .

private readonly IMyService _myService;

public HomeController(IMyService myService)
{
    _myService = myService;
}

public ActionResult AlgumMetodoQualquer()
{
    _myService = new Service();
    // ^ Isso não é possível, porque o campo é readonly
}

In contrast, the code compiles normally when the modifier is removed.

I find this useful in cases like the example you showed in the question, where a service is injected. If it is injected, the field does not need and can not have its value reassigned.

Responding to items: - note that redundancy is purposeful

  

When to use readonly?

When you want the variable not to have its reassigned value in any part of the class other than the constructor.

  

Is there anything I can gain from it?

There is a possibility of making sure the variable will not have its reassigned value in any part of the class other than the constructor.

  

Is there a loss of something using it?

There is a loss of the possibility of reassigning the value of the variable to any part of the class other than the constructor.

  

Why use?

To prevent the value of the variable from being reassigned anywhere in the class other than the constructor.

  

Why not use it?

Do not avoid that the value of the variable be reassigned anywhere in the class other than the constructor.

    
17.05.2018 / 19:07