-3
public class Customer
    {
        private List<Order> _Orders = null;

        public Customer()
        {


        }

        public List<Order> Orders
        {
            get
            {

                if (_Orders == null)
                {
                    _Orders = LoadOrders();
                }
                return _Orders;
            }
        }

        private List<Order> LoadOrders()
        {
            List<Order> temp = new List<Order>();
            Order o = new Order();
            o.OrderNumber = "ord1003";
            temp.Add(o);
            o = new Order();
            o.OrderNumber = "ord1004";
            temp.Add(o);
            return temp;
        }
    }

    public class Order
    {
        public string OrderNumber { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Customer C1 = new Customer();

        }
    }

In the above code there is a class called Customer which is having a private variable of type List which is initialized to null.

We have a public property Orders which has a getter which is used to fill Order list if it is null. There is a LoadOrders() method which fills in orders in List.

Now in Static Void Main I am just creating an object of Class Customer. But when I am debugging the above code I see that Orders object also gets filled up with ord1003 & ord1004.

How Order object gets filled up just by creating an Object of Class Customer ? Can somebody explain ?

If getter is being called I want to know how it is being called automatically while debugging ?

Puneet Pant
  • 918
  • 12
  • 37

1 Answers1

2

There is nothing strange about it. The code is behaving as it should be.

To make it more clear for you. Whenever, we asks for the value of some property, it's getter method is executed. The same is true when we debug our code as well.

So while debugging, if we ask for the value of Orders property, it's getter will be executed and fill the list according to the code. And if do not access the property, the getter method will not be executed for it.

Yogi
  • 9,174
  • 2
  • 46
  • 61