Aamir
Aamir

Reputation: 15546

Why is the output of this program not what I think

I am a little baffled about the output of this program. This is a real scenario from code but I have managed to shorten it to following:

class Program
{
    static void Main(string[] args)
    {
        Dummy obj = new Dummy();
        obj.FillList();
        obj.MyPublicMethod();

    }
}

public class Dummy
{
    public Dummy()
    {
        NamesCollection = new List<string>();
    }
    public ICollection<string> NamesCollection { get; set; }

    private List<string> _names;
    public List<string> Names
    {
        get
        {
            //return _names ??
            //      (_names = NamesCollection.ToList());

            if (ReferenceEquals(_names, null))
            {
                _names = NamesCollection.ToList();
            }

            if (_names.Count != NamesCollection.Count)
            {
                _names.Clear();
                _names.Add("Aamir");
            }
            return _names;
        }
        set { _names = value; }
    }


    public void FillList()
    {
        this.NamesCollection.Add("Atif");
        this.NamesCollection.Add("Ali");
        this.NamesCollection.Add("haris");

        this.Names.Add("Asif");
    }

    public void MyPublicMethod()
    {
        foreach (var item in Names)
        {
            Console.WriteLine(item);
        }
        //I am thinking that output should be:
        //Atif   
        //Ali   
        //haris
        //Aamir  
        //But the output that I am getting is only:
        //Aamir
    }
}

Upvotes: 0

Views: 79

Answers (1)

Chris Shao
Chris Shao

Reputation: 8231

The problem is in your MyPublicMethod method. when you excute the foreach (var item in Names){}, the get method of Names excute. _names.Count = 4, but NamesCollection.Count = 3. so _names be cleared. and add ‘Aamir’.

Upvotes: 3

Related Questions