Skip to main content

What is the Real World use of Copy Constructor in C#

Copy constructor technique is not provided by .NET, but we can write one by our-self,

This type of special constructor will take the paramater as object of its type,

If you want create an object for a class with existing object values and only if you want to change some values the copy constructor will come for help

Example:

We have SalesRep class and we want to move all the reptative values in some set of object then we can re-use this,


    class SalesRep
    {
        public int SalesRepID { get; set; }
        public string SalesRepAddress { get; set; }
        public string VisitingDoctor { get; set; }
        public string DoctorAddress { get; set; }
    }


Writing a normal constructor which picks only the doctor details

        public SalesRep(string pVisitingDoctor, string pDoctorAddress)
        {
            VisitingDoctor = pVisitingDoctor;
            DoctorAddress = pDoctorAddress;
        }




SalesRep DrA_Obj = new SalesRep("Doctor A", "Delhi");
SalesRep DrB_Obj = new SalesRep("Doctor B", "Mumbai");
SalesRep DrC_Obj = new SalesRep("Doctor C", "Bangalore");


Then pass the created doctor object into the Copy Constructor to create the complete object with all values, 

Copy Constructor

public SalesRep(SalesRep pSalesRep, int pSalesRepID, string pSalesRepAddress)
{
            SalesRepID = pSalesRepID;
            SalesRepAddress = pSalesRepAddress;
            VisitingDoctor = pSalesRep.VisitingDoctor;
            DoctorAddress = pSalesRep.DoctorAddress;
}


The complete program:




class SalesRep
    {
        public int SalesRepID { get; set; }
        public string SalesRepAddress { get; set; }
        public string VisitingDoctor { get; set; }
        public string DoctorAddress { get; set; }

        public SalesRep(string pVisitingDoctor, string pDoctorAddress)
        {
            VisitingDoctor = pVisitingDoctor;
            DoctorAddress = pDoctorAddress;
        }
        public SalesRep(SalesRep pSalesRep, int pSalesRepID, string pSalesRepAddress)
        {
            SalesRepID = pSalesRepID;
            SalesRepAddress = pSalesRepAddress;
            VisitingDoctor = pSalesRep.VisitingDoctor;
            DoctorAddress = pSalesRep.DoctorAddress;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            SalesRep DrA_Obj = new SalesRep("Doctor A", "Delhi");
            SalesRep DrB_Obj = new SalesRep("Doctor B", "Mumbai");
            SalesRep DrC_Obj = new SalesRep("Doctor C", "Bangalore");

            Dictionary<int, string> SalesRepDetails = new Dictionary<int, string>();
            SalesRepDetails.Add(10001, "Delhi");
            SalesRepDetails.Add(10002, "Mumbai");
            SalesRepDetails.Add(10003, "Delhi");
            SalesRepDetails.Add(10004, "Mumbai");
            SalesRepDetails.Add(10005, "Delhi");
            SalesRepDetails.Add(10006, "Delhi");
            SalesRepDetails.Add(10007, "Bangalore");
            SalesRepDetails.Add(10008, "Delhi");
            SalesRepDetails.Add(10009, "Bangalore");
            SalesRepDetails.Add(10010, "Mumbai");


            List<SalesRep> LstSalesRepObjects = new List<SalesRep>();

            SalesRep SalesRepObj;
            foreach (KeyValuePair<int, string> SingleSalesRepDetails in SalesRepDetails)
            {
                if (SingleSalesRepDetails.Value == "Delhi")
                {
                    SalesRepObj = new SalesRep(DrA_Obj, SingleSalesRepDetails.Key, SingleSalesRepDetails.Value);
                }
                else if (SingleSalesRepDetails.Value == "Mumbai")
                {
                    SalesRepObj = new SalesRep(DrB_Obj, SingleSalesRepDetails.Key, SingleSalesRepDetails.Value);
                }
                else
                //(SingleSalesRepDetails.Value == "Bangalore")
                {
                    SalesRepObj = new SalesRep(DrC_Obj, SingleSalesRepDetails.Key, SingleSalesRepDetails.Value);
                }
                LstSalesRepObjects.Add(SalesRepObj);
            }

            foreach (SalesRep SingleSalesRepObject in LstSalesRepObjects)
            {
                StringBuilder SbMessage = new StringBuilder();
                SbMessage.Append("Sales Rep with ID " + SingleSalesRepObject.SalesRepID + "   ");
                SbMessage.Append("Living in the address " + SingleSalesRepObject.SalesRepAddress + "   ");
                SbMessage.Append("Visiting the doctor " + SingleSalesRepObject.VisitingDoctor + "   ");
                SbMessage.Append("Who is living in " + SingleSalesRepObject.DoctorAddress + "   ");
                Console.WriteLine(SbMessage.ToString());
            }
            Console.ReadLine();
        }
    }


Output:



Sales Rep with ID 10001   Living in the address Delhi   Visiting the doctor Doctor A   Who is living in Delhi

Sales Rep with ID 10002   Living in the address Mumbai   Visiting the doctor Doctor B   Who is living in Mumbai

Sales Rep with ID 10003   Living in the address Delhi   Visiting the doctor Doctor A   Who is living in Delhi

Sales Rep with ID 10004   Living in the address Mumbai   Visiting the doctor Doctor B   Who is living in Mumbai

Sales Rep with ID 10005   Living in the address Delhi   Visiting the doctor Doctor A   Who is living in Delhi

Sales Rep with ID 10006   Living in the address Delhi   Visiting the doctor Doctor A   Who is living in Delhi

Sales Rep with ID 10007   Living in the address Bangalore   Visiting the doctor Doctor C   Who is living in Bangalore   

Sales Rep with ID 10008   Living in the address Delhi   Visiting the doctor Doctor A   Who is living in Delhi

Sales Rep with ID 10009   Living in the address Bangalore   Visiting the doctor Doctor C   Who is living in Bangalore   

Sales Rep with ID 10010   Living in the address Mumbai   Visiting the doctor Doctor B   Who is living in Mumbai




Ideally copy constructors will be used when reusing the existing values in the created objects to create a new object.


Comments

Popular posts from this blog

Using of global variables in C# - Drawbacks & Solutions

How using global variables can have implications on the design, maintainability, and test-ability of C# code: Harder to understand and reason about the code:       class Program     {         public static int globalCounter = 0;         static void Main()         {             globalCounter++;             Console.WriteLine(globalCounter);         }     }   In this example, the global variable globalCounter is accessible from anywhere in the program, including the Main method. It's not clear where the value of the globalCounter is updated, it could be updated in other methods or classes, making it harder to trace the flow of data and understand the source of bugs.   More prone to errors:       class Program     {         public static string globalString;         static void Main()         {             globalString = "Hello" ;             Method1();             Method2();         }         static void Method1()         {

Task Parallel Library (TPL) and Akka.NET Alternatives

Task Parallel Library (TPL) and Akka.NET are among the most commonly used libraries for parallel and concurrent programming in the .NET ecosystem. However, there are also several other options available, depending on your specific needs: Parallel Language Integrated Query (PLINQ) is a parallel programming feature of .NET that provides an easy and efficient way to perform operations on collections in parallel. LINQ (Language Integrated Query) is a powerful feature in .NET that allows developers to work with data in a more declarative and language-integrated manner. While LINQ queries are inherently sequential, PLINQ extends LINQ by providing parallel versions of the query operators, allowing some queries to execute faster by utilizing multiple processors or cores on a machine. PLINQ is great when you are working with large collections where operations might be CPU-intensive or I/O-bound and could potentially be sped up by parallel execution. Here is a simple example of a PLI

SOLID Principles with Real World examples in C#

  SOLID Principles with Real World examples in C#   SOLID principles are formed by using S Single Responsibility Principles (SRP) O Open Closed Principle (OCP) L Liskov’s Substitution Principle (LCP) I Interface Segregation Principle (ISP) D Dependency Inversion Principle (DIP)   S Single Responsibility Principles (SRP) There should never be more than one reason for a class to change, to be precise one class should have only one responsibility Single Responsibility Principles (SRP) Real world example, A perfect match for SRP is Microservices , a Microservice will not contain functionalities other than the one it is designated to do,  Example ·                   Order Processing Service, ·                   Shipment Management Service, ·                   User Authentication Service, ·                   Catalogue List Service       class OrderProcessor     {         public void Process(Order order)         {             // Check inven