5
Reply

how to create constructors in C#?

Bhushan Gupta

Bhushan Gupta

Sep 16 2013 8:10 AM
1.3k
    class Test1
    {
        //Private fields of class
        int A, B;
        //default Constructor
        public Test1()
        {
            A = 10;
            B = 20;
        }
        //Paremetrized Constructor
        public Test1(int X, int Y)
        {
            A = X;
            B = Y;
        }
        //Method to print
        public void Print()
        {


            Console.WriteLine("A  =  {0}\tB  =  {1}", A, B);
        }


        static void Main()
        {
            Test1 T1 = new Test1();  //Default Constructor is called
            Test1 T2 = new Test1(80, 40); //Parameterized Constructor is called


            T1.Print();
            T2.Print();


            Console.Read();
}}



one more example:


    class Test3
    {
        public Test3()
        {
            Console.WriteLine("Instance  Const");
        }

        static Test3()
        {
            Console.WriteLine("Static  Const");
        }



        static void Main()
        {
            //Static Constructor and instance constructor, both are invoked for first instance.
            Test3 T1 = new Test3();

            //Only instance constructor is invoked.
            Test3 T2 = new Test3();
            Test3 t3 = new Test3();


            Console.Read();
        }
    }


Answers (5)