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

Task Parallel Library (TPL) and Akka.NET: Differences

Task Parallel Library (TPL) and Akka.NET are both powerful tools in the .NET ecosystem for handling parallelism and concurrency, but they serve different purposes and use different models of computation. Here are some key differences:s 1.    Actor Model vs Task-Based Model: Akka.NET is built around the actor model, where actors are the fundamental units of computation and they communicate by exchanging messages. TPL, on the other hand, is task-based. It's designed to make developers more productive by simplifying the process of adding parallelism and concurrency to applications. TPL uses tasks (which are independently executing work units) and provides various ways to control and coordinate them. 2.    Fault Tolerance: One of the key features of Akka.NET is its built-in fault tolerance. It has a "let-it-crash" philosophy, where the system is designed to self-heal from errors. If an actor fails, its parent actor can decide on the supervision strategy: either to resta

Extension Methods - Advanced

Here we will see how can we use the Extension Methods in advanced manner in other types Imagine you often need to retrieve items from a List based on a custom criterion that the built-in LINQ methods don't cover. Extension Methods for Lists: Filtering based on Custom Criteria And the output would be   Extending Enums: Displaying Descriptive Strings Output: Extending DateTime: Calculating Age     Output: The code samples can be found at https://github.com/oneananda/C_Sharp_Examples/tree/main/ExtensionMethods