Saturday, September 13, 2014

Class Constructor

  1. Class Constructor is automatically initialize class field when that instance is created. 
  2. Class Constructor no return values and same name as the class.
  3. If not provide a Class Constructor, default constructor will be used.
  4. Class Constructor can be overloaded by number and type of param.
    class Program
    {
        static void Main()
        {
            Customer c = new Customer();
            c.Printname();

            Customer c1 = new Customer("Water");
            c1.Printname();

            Customer c2 = new Customer("Water","Lily");
            c2.Printname();

            Console.ReadLine();
        }
    }

    class Customer
    {
        string _firstname;
        string _lastname;

        //Default Constructor
        public Customer()
        {
            this._firstname = "Default First Name";
            this._lastname = "Default LastName";
        }

        //Calling another Constructor
        public Customer(string firstname)
            : this(firstname, "No LastName")
        {
        }

        //Parameter Constructor
        public Customer(string firstname, string lastname)
        {
            this._firstname = firstname;
            this._lastname = lastname;
        }

        public void Printname()
        {
            Console.WriteLine(_firstname + " + " + _lastname);
        }

    }

No comments:

Post a Comment