Instance Constructors In C# Part 2

In this article we will learn about Instance constructors in C#.
  • 5756

Introduction

In the previous article we can explain Instance Constructors In C# Part 1. In this article we can learn about copy constructor and private constructor in c#

Copy Constructor

If you create a new object and want to copy the values from an existing object then you can use copy constructor. The purpose of a copy constructor is to initialize a new instance to the values of an existing instance.

Example

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace ProgramCall

{

    class PEPSI

    {

        int A, B;

        public PEPSI(int X, int Y)

        {

            A = X;

            B = Y;

        }

        //Copy Constructor

        public PEPSI(PEPSI P)

        {

            A = P.A;

            B = P.B;

        }

        public void Print()

        {

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

        }

    }

    class CopyConstructor

    {

        static void Main()

        {

            PEPSI P = new PEPSI(10,11);

            //Invoking copy constructor

            PEPSI P1 = new PEPSI(P);

            P.Print();

            P1.Print();

            Console.Read();

        }

    }

}

 

The output of following program

Clipboard190.jpg

Private Constructor
We can use private constructor in C#. Private constructor is created with Private specifier. In C# we can not create an instance of a class which contains at least one private constructor. They are usually used in classes that contain static members only.

Example

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace defaultConstractor

{

    public class like

    {

        private like()   //private constrctor declaration

        {

        }

        public static int currentview;

        public static int visitedCount()

        {

            return ++ currentview;

        }

    }

    class viewCountedetails

    {

        static void Main()

        {

            // like r = new like();   // Error

            Console.WriteLine("-------Private constructor----------");

            Console.WriteLine();

            like.currentview = 100;

            like.visitedCount();

            Console.WriteLine("Now the view count is: {0}", like.currentview);

            Console.ReadLine();

        }

    }

}

 

 The output of following program

 Clipboard191.jpg

© 2020 DotNetHeaven. All rights reserved.