This post series we will go through the understanding of the lock statement, monitor, mutex, and semaphore available in C#.
All of these classes provide a synchronization mechanism to protect the shared code or resources in a multithreadedapplication.
Let’s first understand the lock statement in C#.
C# Lock Statement
Lock Statement: In C#, the lock is a synchronization mechanism that allows only one thread to access a specified piece of code or a common field at a time.
It is mainly used to achieve an exclusive lock to avoid inconsistent output while reading and writing to a common variable in a multithreaded environment.
Generally, the lock keyword is placed around a critical section of code, where we want to allow only one thread to access the resource at a time. All the other threads have to wait and halt the execution until the locked object is released.
Pictorial representation of mutual exclusion of lock
Introduction: In C#, Reflection is a process of inspecting or modifying metadata of an assembly at the runtime.
Reflection allows us to create an instance of a type without using the ‘new‘ operator and to invoke its methods, fields, and properties dynamically. To work with reflection in .Net, we must include the System.Reflection namespace in our program.
Private constructor: In C#, A parameterless constructor with a private access modifier in a class is known as a private constructor. It is a special instance constructor which is mainly used to control the instantiation of a class.
The main intension behind private constructor is to control the object creation and to stop explicit inheritance.
Now in this post, I’ll explain in details about the copy constructor with example.
Copy Constructor in C#
C# does not provide a copy constructor for the objects but as a developer, we can write one by ourselves based on our requirement.
Copy constructor: In C#, A parameterized constructor that takes the same type of object as a parameter is called a copy constructor.
The copy constructor is useful when we want to copy data from the existing object to the new object without affecting the values of the existing object. In simple words, copy constructor means cloning of data from one object to the other object.
Note: To create a copy constructor we must have more than one constructor in a class.