BobSwanson
BobSwanson

Reputation: 423

List with private setter

I'm trying to allow users of my class to be able to add to list, not set. Hence I would like to have a private set like so:

public class Model
{
    private IList<KeyValuePair<string, int>> pair;

    public Model()
    {
        pair = new List<KeyValuePair<string, int>>();
    }

    public IList<KeyValuePair<string, int>> Pair 
    {
        get
        {
            return pair.Where(x => x.Value > 0
                                          && !string.IsNullOrEmpty(x.Key)).ToList();
        }
        private set { pair = value; }
    }

However when I add to Pair.Add() it doesn't work.

I've tried this (which works) but then I need the "Where" clause in get{}. How would I do it?

public class Model
{
    public Model()
    {
        Pair = new List<KeyValuePair<string, int>>();
    }
    public IList<KeyValuePair<string, int>> Pair { get; private set; }
}

Upvotes: 0

Views: 821

Answers (2)

Frode
Frode

Reputation: 3455

I would probably solved it with a method

public class Model
{
    private readonly Dictionary<string, int> pairs = new Dictionary<string, int>();

    public void Add(string key, int value)
    {
        pairs[key] = value;
    }

    public IEnumerable<KeyValuePair<string, int>> GetPairs()
    {
        return from pair in pairs
               where pair.Value > 0 && string.IsNullOrEmpty(pair.Key) == false
               select pair;
    }
}

Upvotes: 1

Rion Williams
Rion Williams

Reputation: 76547

If you want to use this approach, you would probably want to implement a public Add() method within this class in order to add elements to the underlying private property :

public class Model
{
        // Other code omitted for brevity

        public bool Add(KeyValuePair<string,int>> item)
        {
             // Add your item to the underlying list
             pair.Add(item);
        }
}

Presumably, you were using the results from your Model.Pair and attempting to add to it, which won't work as expected (as Model.Pair would be just returning a copy of your list and not the actual list itself).

Upvotes: 2

Related Questions