2

I have a class with a private set to List<string>, so I can not set this list.

This is my class:

public class PaginationReturn<T>
{
    public PaginationReturn()
    {
        this.Errors = new List<string>();
        this.Success = true;
    }

    public IEnumerable<T> Data { get; set; }
    public Boolean Success { get; private set; }
    public List<string> Errors { get; private set; }

    public void AddError(String mensagem)
    {
        this.Errors.Add(mensagem);
        this.Success = false;
    }
}

I don't want to allow to do something like this, but this compiles without error:

paginationReturn.Errors.Add("Error!!");

I want to force to use this method to add items to a list:

paginationReturn.AddError("Error!!");
William
  • 502
  • 1
  • 9
  • 27
  • 3
    Then you will need to make that `List` private or expose it as an `IEnumerable` – Camilo Terevinto Jan 03 '18 at 12:23
  • I was going to suggest `IReadOnlyCollection` but the suggested `IEnumerable` seems like a simpler and easier approach if you want to continue exposing `.Errors`. while the former does state intent. https://stackoverflow.com/questions/24880268/ienumerable-vs-ireadonlycollection-vs-readonlycollection-for-exposing-a-list-mem – Nkosi Jan 03 '18 at 12:26

2 Answers2

7

One approach is to make the errors list that you have private and expose a read-only version of it to the outside world. Like this:

public class PaginationReturn<T>
{
    public PaginationReturn()
    {
        this._errors = new List<string>();
        this.Success = true;
    }

    public IEnumerable<T> Data { get; set; }
    public Boolean Success { get; private set; }
    private List<string> _errors;

    public IReadOnlyList<string> Errors
    {
        get
        {
            return _errors.AsReadOnly();
        }
    }

    public void AddError(String mensagem)
    {
        this._errors.Add(mensagem);
        this.Success = false;
    }
}

For .NET 4.0:

You can replace IReadOnlyList<string> with IEnumerable<string> and AsReadOnly with AsEnumerable.

Zein Makki
  • 29,485
  • 6
  • 52
  • 63
1

Since the List has public get, the client will be able to invoke methods on it. Making private set will ensure that client is not able to point paginationReturn.Errors to another List.

One option is to have private List< string > as field member, say _Errors. And have public wrapper property of type IEnumerable< string > around the _Errors.

Abhijeet Nagre
  • 876
  • 1
  • 11
  • 21