Why is this field declared as private and also readonly?

Sergio Tapia picture Sergio Tapia · Jun 13, 2010 · Viewed 22.7k times · Source

In the following code:

public class MovieRepository : IMovieRepository
{
    private readonly IHtmlDownloader _downloader;

    public MovieRepository(IHtmlDownloader downloader)
    {
        _downloader = downloader;
    }

    public Movie FindMovieById(string id)
    {
        var idUri = ...build URI...;

        var html = _downloader.DownloadHtml(idUri);

        return ...parse ID HTML...;
    }

    public Movie FindMovieByTitle(string title)
    {
        var titleUri = ...build URI...;

        var html = _downloader.DownloadHtml(titleUri);

        return ...parse title HTML...;
    }
}

I asked for something to review my code, and someone suggested this approach. My question is why is the IHtmlDownloader variable readonly?

Answer

Eric J. picture Eric J. · Jun 13, 2010

If it's private and readonly, the benefit is that you can't inadvertently change it from another part of that class after it is initialized. The readonly modifier ensures the field can only be given a value during its initialization or in its class constructor.

If something functionally should not change after initialization, it's always good practice to use available language constructs to enforce that.