Thursday 29 September 2016

Constructors in C Sharp Example and Code

/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;



/*
 
  Definition:
  It is used to initialized the member variables of class.
  It is just like a method which doesn't have return type.
  A class could have many constructors based on parameters.
  No need to calls explicitly.
  Call automatically while we create instance of class.
 
 */

namespace Constructors_In_CSharp
{
    class Program
    {
        int age;
        string name;

        public Program()
        {
            age = 18;
            name = "Unknown";
        }

        public Program(string inpuName)
        {
            age = 18;
            name = inpuName;
        }

        public Program(string inpuName, int inputAge)
        {
            Console.WriteLine("3rd constructor called");
            Console.WriteLine("Age:" + inputAge.ToString());
            Console.WriteLine("Name:" + inpuName.ToString());

        }



        public void print()
        {
            Console.WriteLine("Age:" + age.ToString());
            Console.WriteLine("Name:" + name.ToString());
        }
        static void Main(string[] args)
        {
            Program p = new Program();
            p.print();

            Program p1 = new Program("raj kumar");
            p1.print();


            Program p2 = new Program("raj kumar", 28);


            Console.ReadLine();
        }
    }
}