Constructor overloading in C#

Constructors need to be overloaded depending on what extend of data/properties need to be initialized in order to set the object to a particular state. Below a good example using a Customer / Orders example. Note that Customer constructor is overloaded in 3 different ways based on what data need to be initialized. Here we use the third implementation so we set the desired id and name for the Customer. Note how we use the this operator to recursively invoke the other constructors.

public class Order
   {
       public int OrderId;
   }

class Customer
    {
        public int ID;
        public string Name;
        public List<Order> Orders;
 
        public Customer()
        {
            this.ID = 2131;
            this.Name = "John Smith";
            this.Orders = new List<Order>();
        }
 
        public Customer(int id)
            : this()
        {
            this.ID = id;
        }
 
        public Customer(int id, string name)
            : this(id)
        {
            this.Name = name;
        }
    }
 
    class Program
    {
        public static void Main(string[] argvs)
        {
            var Cust = new Customer(45345"James");
            
            Cust.Orders.Add(new Order() { OrderId = 123 });
            Cust.Orders.Add(new Order() { OrderId = 456 });
            Cust.Orders.Add(new Order() { OrderId = 789 });
            Console.WriteLine("Customer " + Cust.Name + " (" + Cust.ID + ") has below
 orders >\n");
            foreach (var i in Cust.Orders)
            {
                Console.WriteLine(i.OrderId + "\n");
            } 
 
        }
 
    }


Add a Comment

Your email address will not be published. Required fields are marked *