0% found this document useful (0 votes)
25 views

DotNetTutorials in C# Notes

Uploaded by

rupams2024
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

DotNetTutorials in C# Notes

Uploaded by

rupams2024
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 65

What is an Event?

Events are notifications. In simple words, we can say that it’s a message that goes out to one or more
people (we can also say them as subscribers) who are listening. Obviously, it’s not going to be people
in .NET, it will be objects.

Events are playing a central role in .NET Framework. They are an important part of the .NET Framework
and you can see them all over the place when you type anything in visual studio, if you have ever seen a
lightning bulb type icon, then that’s an event.

Events provide a way to trigger notifications. So, you could think of a user who talks bullhorn or loudly to
announce something to a group of people that something is going to happen like the part is about to start
or the present ceremony is going to start. That is also an event from the human world.

In the Programming world, an event is also the same thing, it is just that instead of having this bullhorn or
instead of talking loudly, here, we are going to notify using .NET Events. And then we will also use
something called Delegates, EventArgs, and EventHandlers.

Object-Oriented Programming is a strategy that provides some principles for developing applications or
software. It is a methodology. Like OOPs, other methodologies exist, such as Structured Programming,
Procedural Programming, or Modular Programming. But nowadays, one of the well-known and famous
styles is Object Orientation, i.e., Object-Oriented Programming.

The Object Orientation all depends on how we see the internal system or understand the internal system.
So, if you understand the system ideally and if your perspective is very clear, you can develop a better
system.

we are taking an example of a bank. If you’re developing an application for a bank using modular
programming, how do you see the system, how do you see the workings of a bank, and what will be your
design? That depends on how you understand it and how you see the system. So, let us see how we look
at the bank system using modular programming.

In a bank, you can open an account, you can deposit an amount, you can withdraw an amount, you can
check your account balance, or you can also apply for a loan, and so on. So, these are the things that you
can do at the bank.

So, Opening an Account, Depositing Money, Withdrawing Money, Checking Your Balance, and
Applying For a Loan are functions. All these are nothing but functions. And you can do the specific
operations by calling that specific function. So, if you’re developing software for a bank, it is nothing but a
collection of functions. So, the bank application will be based on these functions, and the user of the bank
application will be utilizing these functions to perform his required task. So, you will develop software as a
set of functions in Modular Programming.

Now, for Object Orientation, we would take some different examples. The government provides many
services like electric, water supply, education, and transport, and even the government can have banks.
So, these are the different departments of a government. Now, what can you do in the electric department
as a user? You can apply for a new connection, you can close your connection if you have extra
connections, or you can make a bill payment. What are these? These are functions belonging to the
Electric Department.

Now, in the same way, the bank is also there. The same functions like account opening, deposit, withdraw,
check balance, apply for a loan, etc., are also there. These are functions belonging to the Bank.

1
What do we call these? We call them objects. So, the complete system for the government or a complete
software for a government is a collection of objects. Now, each object has its relevant functions. So,
complete software is a collection of objects containing functions and data related to those functions.

In Modular Programming, the system was a collection of functions. So, if you compare them now, in
modular programming, we are looking at the very close level, and in object-oriented programming, we are
looking at a little far away level.

Why Object Orientation?

Let us talk about a manufacturing firm which manufactures cars or vehicles. If you look at that
manufacturing farm, then it may be working in the form of departments like one is an inventory department
that maintains the stock of raw materials and one is manufacturing, which is the production work that they
do, and one department will be looking at sales and one department is looking at marketing. One is about
payroll, and one is for accounts, and so on. So, there may be many departments

Suppose you are developing software only for payroll or inventory purposes. In that case, you may look at
the system just like a modular approach, and in that, you can find functions like placing an order and
checking the item in stock. These types of things can have a set of functions so that you can develop the
software only for the inventory system as a collection of functions. Still, when developing software for the
entire organization, you must see things in objects.

So, the inventory item is an object, an employee is an object, an account is an object, and a product
manufacturer is an object. The machines used for production are an object. So, all these things are
objects. Here, you need to see things in the form of objects and define their data and the functions that
they’re performing. We are looking at the system at a higher level. So, we can adopt object orientation.

What are the Problems of Modular Programming?

Modular programming has the following problems.

1. Reusability
2. Extensibility
3. Simplicity
4. Maintainability

Reusability: In Modular Programming, we must write the same code or logic at multiple places,
increasing code duplication. Later, if we want to change the logic, we must change it everywhere.

Extensibility: It is not possible in modular programming to extend the features of a function. Suppose you
have a function and you want to extend it with some additional features; then it is not possible. You have to
create an entirely new function and then change the function as per your requirement.

Simplicity: As extensibility and reusability are impossible in Modular Programming, we usually end up with
many functions and scattered code.

Maintainability: As we don’t have Reusability, Extensibility, and Simplicity in modular Programming, it is


very difficult to manage and maintain the application code.

How Can We Overcome Modular Programming Problems?

2
We can overcome the modular programming problems (Reusability, Extensibility, Simplicity, and
Maintainability) using Object-Oriented Programming. OOPs provide some principles, and using those
principles, we can overcome Modular Programming Problems.

What Is Object-Oriented Programming?

Let us understand Object-Oriented Programming, i.e., OOP concepts using C#. Object-oriented
programming (OOPs) in C# is a design approach where we think in terms of real-world objects rather than
functions or methods. Unlike procedural programming language, in OOPs, programs are organized around
objects and data rather than action and logic. Please have a look at the following diagram to understand
this better.

Reusability:

To address reusability, object-oriented programming provides something called Classes and Objects. So,
rather than copy-pasting the same code repeatedly in different places, you can create a class and make an
instance of the class, which is called an object, and reuse it whenever you want.

Extensibility:

Suppose you have a function and want to extend it with some new features that were impossible with
functional programming. You have to create an entirely new function and then change the whole function
to whatever you want. OOPs, this problem is addressed using concepts called Inheritance, Aggregation,
and Composition. In our upcoming article, we will discuss all these concepts in detail.

Simplicity:

Because we don’t have extensibility and reusability in modular programming, we end up with lots of
functions and scattered code, and from anywhere we can access the functions, security is less. In OOPs,
this problem is addressed using Abstraction, Encapsulation, and Polymorphism concepts.

Maintainability:

As OOPs address Reusability, Extensibility, and Simplicity, we have good, maintainable, and clean code,
increasing the application’s maintainability.

What are the OOPs Principles or OOPs Concepts in C#?

OOPs provide 4 principles. They are

1. Encapsulation
2. Inheritance
3. Polymorphism
4. Abstraction

3
Note: Don’t consider Class and Objects as OOPs principle. We use classes and objects to implement
OOP Principles.

Let’s understand the definitions of the OOPs Principle in this session. From the next article onwards, we
will discuss all these principles in detail using some real-time examples.

What are Abstraction and Encapsulation?

The process of representing the essential features without including the background details is
called Abstraction. In simple words, we can say that it is a process of defining a class by providing
necessary details to the external world, which are required by hiding or removing unnecessary things.

The process of binding the data and functions together into a single unit (i.e., class) is
called Encapsulation. In simple words, we can say that it is a process of defining a class by hiding its
internal data members from outside the class and accessing those internal data members only through
publicly exposed methods or properties. Data encapsulation is also called data hiding because, using this
principle, we can hide the internal data from outside the class.

Abstraction and Encapsulation are related to each other. We can say that Abstraction is logical thinking,
whereas Encapsulation is its physical implementation.

Understanding Abstraction and Encapsulation with an Example:

Let us understand Abstraction and Encapsulation Principles with an example. Suppose you want to design
one class for providing the register functionality of a user. For that, what you need to do is first you need to
get the data and validate the data, then you need to get the connection string for the database, and finally,
you need to save the data in the database. And for this, you have three methods, i.e., Validate,
GetConnectionString, and SaveUser. If you provide access to these three methods to the users of this
class, then he may end up calling these methods in the wrong order, or it may be possible that he may
forget to call any of these methods.

Advertisements
So, here, you need to create one method called Register, and as part of that method, you need to call all
these methods (Validate, GetConnectionString, and SaveUser) in a proper sequence. Finally, you need to
give access to the Register method instead of the Validate, GetConnectionString, and SaveUser methods.
This is what we discussed is nothing but abstraction. How you implement this is nothing but encapsulation.
So, here, you need to create the Validate, GetConnectionString, and SaveUser methods with a private
access specifier so the user cannot access these methods. Make the Register method Public so the user
can access this method, as shown below.

We can achieve code Simplicity through Encapsulation and Abstraction.

What is Inheritance?

The process by which the members of one class are transferred to another class is called inheritance.
The class from which the members are transferred is called the Parent/Base/Superclass, and the class
that inherits the Parent/Base/Superclass members is called the Derived/Child/Subclass. We can achieve
code extensibility through inheritance.

What is Polymorphism?

4
Polymorphism is derived from the Greek word, where Poly means many and morph means faces/
behaviors. So, the word polymorphism means the ability to take more than one form. Technically, we can
say that the same function/operator will show different behaviors by taking different types of values or with
a different number of values, called Polymorphism. There are two types of polymorphism.

1. Static polymorphism/compile-time polymorphism/Early binding


2. Dynamic polymorphism/Run time polymorphism/Late binding
Static polymorphism is achieved by function overloading and operator overloading, whereas dynamic
polymorphism is achieved by function overriding.

Why do we need Object-Oriented Programming (OOPs) in C#?

If you want to represent real-world objects in a programming language for automating the business by
achieving Reusability, Extensibility, Simplicity, and Maintainability, then you need the concept of
OOPs. OOPs provide some principles, and by using those principles, we can develop real-world objects in
a programming language by achieving Reusability, Extensibility, Simplicity, and Maintainability.

All living and non-living things are considered objects. So real-world objects such as Persons, Animals,
Bikes, Computers, etc., can be developed in object-oriented programming languages by using the OOPs
concept.

Why do we need real-world objects in a Project?

We need real-world objects in a project because real-world objects are part of our business. As we are
developing applications (software) for automating the business, we must create business-related real-
world objects in the project.

For example, to automate the Bank business, we must create real-world objects like Customers,
Managers, Clerks, Office Assistants, Marketing Executives, Computers, Printers, Chairs, tables, etc. So,
along with the Bank object, we must also create all the above objects because, without all the above
objects, we cannot run a Bank business. Technically, we call the above objects business objects.

What types of programming languages come under the OOP system?

The programming languages that implement all the four principles provided by OOPs are called object-
oriented programming languages, for example, Java, C#, C++, etc.

Advantages of OOP in C#:

Here’s a summary of the key advantages and disadvantages of using OOP concepts in C#:

 Modularity: OOP promotes modular code by encapsulating data and behavior within classes. This
makes managing and maintaining large codebases easier since you can work on individual classes
independently.
 Code Reusability: Inheritance allows you to create new classes by reusing existing ones (base
classes). This reduces code duplication and promotes a “write once, use many times” approach.
 Abstraction: OOP allows you to create abstract classes and interfaces that define a contract without
providing implementation details. Abstraction simplifies complex systems by hiding unnecessary
details.
 Polymorphism: Polymorphism enables you to write code that can work with objects of different
classes through a common interface or base class. This flexibility simplifies code and allows for
extensibility.
 Encapsulation: Encapsulation restricts access to the internal state of objects, promoting data
integrity and security. You can control access to fields and methods using access modifiers like
public, private, protected, and internal.
 Maintenance and Debugging: OOP’s modular and organized structure makes debugging and
maintaining code easier. Changes in one class typically have limited impact on other parts of the
code.
 Scalability: OOP principles can help create scalable and extensible software systems. New features
can often be added by creating new classes and extending existing ones without modifying the
existing code.
 Readability: OOP promotes code that is more human-readable and self-explanatory. Classes and
objects map closely to real-world entities and interactions, making it easier for developers to
understand the code’s purpose.

5
Points to Remember:

1. Object-oriented programming Principles or OOP Concepts in C# are design principles that suggest
how we should develop a program so that we can reuse it from other layers of the project effectively
and with high scalability.
2. Scalability means we have to develop the project in such a way that it should accept future changes
without making major changes to the project. Small changes also should be accepted from external
files like properties files, XML files, etc. Scalability is achieved by developing classes by integrating
them in a loosely coupled way.
3. We should develop the project with scalability as there will be business growth. Due to the business
growth, we must add required changes to the project with minimal modifications.
4. As a developer, we must remember that in the initial stage of business, the customer never makes a
significant investment. As the business grows, customers increase investment according to the
growing requirements added to the projects. To add those new requirements, we should not design
the project entirely.
5. So, we must strictly design the project by following OOP principles, even though they are not needed
at the initial stage, but for accepting future changes.
In the next article, I will discuss the Class and Objects in C# with Examples. In this article, I explain the
basics of Object-Oriented Programming (OOPs) in C#. I hope you enjoy the OOPs Concept in the C#
article.

Class and Objects in C# with Examples

In this article, I am going to discuss Class and Objects in C# with examples. Please read our previous
article before proceeding to this article where we discussed the basic concepts of Object-Oriented
Programming. Understanding class and objects in C# is very important for you as a developer. This is
because everything in C# is in the form of class and objects. As part of this article, we are going to discuss
the following pointers in detail.

1.Class and Objects from Layman’s Point of View.


2.Class and Objects from Programming Language Point of View.
3.How can we create a Class and Object in C#?
4.Difference between Class and Objects in C#
5.Types of classes in C#
Class and Objects in C#

As we already discussed in our previous article, class, and objects addresses the reusability functionality.
Again we discussed in Object-Oriented Programming, we need to think in terms of objects rather than
functions. So, let us discuss what exactly classes and objects are from the Layman point of view as well as
from the programming point of view.

Class and Objects from Layman’s Point of View.

Most people will say that everything that you can see and touch in the world is an object and there is a
class for it. So let us understand what it means. Classes come from classification. If you take anything in
the world you can say that this belongs to so-and-so class. If you take a group of students at a college then
you can say that these students belong to computer science, and this is a class of computer science and
these students belong to electronics and this is the class of electronics.

So, here, we are classifying based on the subject or the course they are going through. It means that
classification is based on the criteria that we are adopting.

So, classification is done based on some criteria or the common things that you can find in them. We
define classes in our daily life. Any 4-wheeler vehicle in which there is a driver and some people are sitting
at the back or beside the driver, then we say it’s a car. So, this is the classification depending on the
property we are defining. So, based on the properties we can define whether it is a truck or it is a car and
both are vehicles again, so the vehicle is again a class.

If we take examples of human beings, it is a class. There’s a class human and you are an object of human
being class. The BMW is a car and Toyota is also a car. These are the objects of class cars. So, class is a
definition and objects are instances.

Some companies provide housing facilities for their employees. They will have some cargo or apartments
or independent houses. All the apartments will be similar because they follow the same design. So, design

6
is one and there are the houses or the apartments or the flats that are based on the design. This design is
nothing but class and the houses created with the help of that design are objects.

Design is nothing but the blueprint of the house object. So, the house will be having all those things that
are defined in the design plan or in the blueprint.

So, every engineer does some paperwork or designing work, and based on that design the manufacturing
is done. When you make a product, that product will be having all those things that are there in the design
and you can then make many products based on that design.

A car company will design a new car. Then they will manufacture many cars based on that design. So, all
those cars are objects and the design that the company is holding with them is a class. In the same way,
we also want to write a class and create objects in our program.

Class and Objects from Programming Language Point of View.

Here we are going to understand the class and objects from the C# programming language point of view.
But this is also applicable to any object-oriented programming language like java and C++.

Class:

A class is simply a user-defined data type that represents both state and behavior. The state represents
the properties and behavior is the action that objects can perform. In other words, we can say that a class
is the blueprint/plan/template that describes the details of an object. A class is a blueprint from which the
individual objects are created. In C#, a Class is composed of three things i.e. a name, attributes, and
operations.

Objects:

It is an instance of a class. A class is brought live by creating objects. An object can be considered as a
thing that can perform activities. The set of activities that the object performs defines the object’s
behavior. All the members of a class can be accessed through the object. To access the class members,
we need to use the dot (.) operator. The dot operator links the name of an object with the name of a
member of a class.

How can we create a Class and Object in C#?

Let us understand how to create class and object in C#. In order to understand this, please have a look at
the following image. As you can see in the below image, a class definition starts with the
keyword class followed by the class name (here the class name is Calculator), and the class body is
enclosed by a pair of curly braces. As part of the class body, you define class members (properties,
methods, variables, etc.). Here as part of the body, we define one method called CalculateSum. The class
Calculator is just a template. In order to use this class or template, you need an object. As you can see in
the second part of the image, we create an object of the class Calculator using the new keyword. And then
store the object reference on the variable calObject which is of type Calculator. Now, using this calObject
object we can access the class members using a dot.

7
So, the point that you need to remember is, to create a class you need to use the class keyword while if
you want to create an object of a class then you need to use the new keyword. Once you create the object
then you can access the class members using the object.

The complete example code is given below.

using System;
namespace ClassObjectsDemo
{
class Program
{
static void Main(string[] args)
{
//Creating object
Calculator calObject = new Calculator();
//Accessing Calculator class member using Calculator class object
int result = calObject.CalculateSum(10, 20);
Console.WriteLine(result);
Console.ReadKey();
}
}
//Defining class or blueprint or template
public class Calculator
{
public int CalculateSum(int no1, int no2)
{
return no1 + no2;
}
}
}
Output: 30

Difference between Class and Objects in C#

Many programmers or developers still get confused by the difference between class and object. As we
already discussed, in object-oriented programming, a Class is a template or blueprint for creating Objects,
and every Object in C# must belong to a Class. Please have a look at the following diagram to understand
the difference between them.

As you can see in the above image, here we have one class called “Employee”. All the Employees have
some properties such as employee id, name, salary, gender, department, etc. These properties are
nothing but the attributes (properties or fields) of the Employee class.

8
If required you can also add some methods (functions) that are common to all Employees such as
InsertData and DisplayData to insert and display the Employee Data.

So, the idea is that the template or blueprint of the Employee is not going to change. Each and every
Object is going to build from the same template (Class) and therefore contains the same set of methods
and properties. Here, all Objects share the same template but maintain a separate copy of the member
data (Properties or fields).

For example: If we create two employees, let’s say Emp1 and Emp2, then both Emp1 and Emp2 are
Employees, so they can be classified as belonging to the Employee class. Both have the same methods
(InsertData and DisplayData) but are different in models (properties or fields).

Types of Classes in C#:

Please have a look at the following image.

In C# we have the below types of classes

1. Abstract Class
2. Concrete class
3. Sealed Class
4. Partial Class
5. Static Class
We will discuss each of these classes in detail in our upcoming articles. Here, in this article, I try to
explain Class and Objects in C#. I hope you understood this Class and Objects in C# article. In the next
article, I am going to discuss Constructors in C# and their types in detail with Examples.

Constructors in C# with Examples

In this article, I am going to discuss Constructors in C# with Examples. Please read our previous article
before proceeding to this article where we discussed how to create classes and objects in C# with
examples. Object-Oriented Programming is all about writing code inside a class. A class is a collection of
members like fields, methods, constructors, etc. Inside a class one of the most important members present
is called Constructor.

What is a Constructor in C#?(Read-18-April,Revision-20-April,Rerevise-24-


April))
It is a special method present inside a class responsible for initializing the variables of that class. We will
come to this point later part of this article.

The name of the constructor method is exactly the same name as the class in which it was present. You
cannot change the name. If your class name is Employee, then the name of the constructor method is
going to be Employee, and if your class name is Student, then the constrictor name is also going to be
Student.

The constructor method does not return any value. That means it is a non-value returning method.
Generally, methods are of two types i.e. value returning and non-value returning and constructors are
purely non-value returning. That is, they never return any value.

Example to Understand Constructor in C#

9
Each and every class requires this constructor if we want to create the instance of the class. If we don’t
have a constructor, then we cannot create an instance of the class. At this point, you have one doubt,
earlier we defined many classes but we never used a constructor, but still, we are able to create the
instance of the class, how? Let us clarify this doubt. Suppose, we have a class as follows:

class Test
{
int i;
}
Then, we create an instance of the above Test class somewhere in our application as follows:

Test obj = new Test();

Is the above statement valid? Yes, it is valid. The reason is that it is the responsibility of a programmer to
define a constructor under his class and if he/she fails to do, on behalf of the programmer an implicit
constructor gets defined in that class by the compiler. For a better understanding, please have a look at
the below diagram which shows the code before and after compilation.

You can see here that after compilation, the compiler adds the public constructor to the class and initializes
the variable and this is the responsibility of a constructor i.e. initializing the variables of that class. Here, it
is initializing the variable with 0. If a class variable is initialized implicitly means that is done by a
constructor.

Every variable we declared inside a class and every field we declared inside a class has a default value.
All numeric types are initialized with 0, Boolean types initialized with false, and string and object types
initialized with null. For a better understanding, please have a look at the below image.

Like this, the initialization is performed for each and all variables present in the class and this is the
responsibility of the constructor. That is why a constructor is very important for us inside a class.

10
We are not assigning a value, but a value is coming there means someone has assigned the value to
these variables. So, who is going to do that? The constructor is going to do that. And this constructor is not
defined by us. Then who defined this constructor? The compiler defined this constructor for us. And we call
this an Implicit Constructor. And if we defined the same thing, then it is called an explicit constructor.

Points to Remember while working with Constructors in C#:

1. Implicitly Defined Constructors are parameter less and these constructors are also known as Default
Constructors. This is because they are used to initialize the variables with default values.
2. Implicitly Defined Constructors are public. If you see in our example, we define the class Test with a
default access specifier but the constructor is public which is generated by the compiler.
3. We can also define a constructor under the class and if we define it, we can call it an Explicit
Constructor and an Explicit Constructor can be parameter less and parameterized also.

Example to Understand Implicitly Constructor in C#:

In the below example, we are creating a class with three variables and in the class, we have not defined
any constructor explicitly. So, here compiler will provide the implicit constructor and will initialize the
variables with the default value. Then from the Main method, we create an instance of the class and print
the values of the variables and it should print the default values based on the variable type. For example,
for int, the default value is 0, for bool the default value is false, and for string or object the default is null.
And this default initialization is done by the implicit constructor which is given by the compiler.

using System;
namespace ConstructorDemo
{
class Program
{
static void Main(string[] args)
{
Test obj = new Test();
Console.WriteLine($"i = {obj.i}");
Console.WriteLine($"b = {obj.b}");
//value null will be printed, so here we checking the null
if (obj.s == null)
{
Console.WriteLine("s = null");
}
Console.ReadKey();
}
}
class Test
{
public int i;
public bool b;
public string s;
}
}
Output:

How to Define the Constructor Explicitly in C#?

We can also define the constructor explicitly in C#. The following is the explicit constructor syntax.

11
Whenever we are creating an instance, there will be a call to the class constructor. For a better
understanding, please have a look at the below example. Here, we defined one parameter less constructor
explicitly, and then from the Main method, we create an instance. When we create the instance, it will
make a call to the constructor, and the statements written inside the constructor will be executed. In this
case, it will execute the print statement in the console.

using System;
namespace ConstructorDemo
{
class Program
{
static void Main(string[] args)
{
ExplicitConstructor obj = new ExplicitConstructor();
Console.ReadKey();
}
}
class ExplicitConstructor
{
public ExplicitConstructor()
{
Console.WriteLine("Explicit Constructor is Called!");
}
}
}
Output: Explicit Constructor is Called!

One more important point that you need to remember is, how many instances you created, and that many
times the constructor is called for us. Let us prove this. Please modify the example code as follows. Here, I
am creating the instance four times and it should and must call the constructor 4 times and we should see
the print statement four times in the console window.

using System;
namespace ConstructorDemo
{
class Program
{
static void Main(string[] args)
{
ExplicitConstructor obj1 = new ExplicitConstructor();
ExplicitConstructor obj2 = new ExplicitConstructor();
ExplicitConstructor obj3 = new ExplicitConstructor();
ExplicitConstructor obj4 = new ExplicitConstructor();
Console.ReadKey();
}
}
class ExplicitConstructor
{
public ExplicitConstructor()
{
Console.WriteLine("Explicit Constructor is Called!");
}
}
}
Output:

12
We should not use the word Implicitly while calling the constructor in C#, why?

See, if we are not defining any constructor explicitly, then the compiler will provide the constructor which is
called Implicitly Constructor. See, the following example. If you move the mouse pointer over the Test
class, then you will see the following. Here, Test is a class present under the ConsructorDemo
namespace.

Now, move the mouse pointer to Test() as shown in the below image. Here, the first Test is the class name
and the second Test() is the constructor. That means we are calling the constructor explicitly.

Here, we are explicitly making a call to the constructor and when we call the constructor, the implicit
constructor which is provided by the compiler is called and will initialize the variables.

Now coming to the ExplicitConstructor example, we are also doing the same thing. Please have a look at
the below example. If you move the mouse pointer over the ExplicitConstructor class, then you will see the
following. Here, ExplicitConstructor is a class present under the ConsructorDemo namespace.

13
Now, move the mouse pointer to ExplicitConstructor() as shown in the below image. Here, the first
ExplicitConstructor is the class name and the second ExplicitConstructor() is the constructor. That means
we are calling the constructor explicitly.

Here, we are explicitly making a call to the constructor and when we call the constructor, the explicit
constructor which is provided by us is called and will initialize the variables. So, here you might be
confused with terms. Defining and calling.

Defining and Calling Constructor in C#:

Defining: Defining a constructor means implementing a constructor in your class. Defining can be two
types i.e. Implicit and Explicit. Implicit means the compiler will define the constructor. Explicit means we as
a programmer define the constructor. The following code shows defining a constructor explicitly.

14
Calling: Whenever we are creating the instance, we are calling the constructor. Calling is Explicit. We
should only call. There is no implicit call to the constructor. For a better understanding, please have a look
at the below code.

The calling should be done explicitly by us. That may be an implicit or explicit constructor but calling the
constructor should be explicit.

Frequently Asked Interview Questions:

What is a Constructor in C#?

In simple words, we can define the constructors in C# are the special types of methods of a class that are
executed whenever we create an instance (object) of that class. The Constructors are responsible for two
things. One is the object initialization and the other one is memory allocation. The role of the new keyword
is to create the object and the role of the constructor is to initialize the variables.

What are the rules to follow while working with C# Constructor?

1. The constructor’s name should be the same as the class name.


2. It should not contain a return type even void also.
3. As part of the constructor body return statement with a value is not allowed.
What does a Constructor have in C#?

1. It can have all five accessibility modifiers i.e. public, private, protected, etc.
2. The constructor can be parameterless or parameterized.
3. It can have a throws clause which means we can throw an exception from the constructor.
4. The constructor can have logic, as part of logic it can have all C#.NET legal statements except return
statements with value.
5. We can place a return; in the constructor.
Syntax:

15
Can we define a method with the same class name in C#?

No, it is not allowed to define a method with the same class name in C#. It will give you a compile-time
error. For a better understanding, please have a look at the below image.

In the next article, I am going to discuss the various Types of Constructors in C# with Examples. Here,
in this article, I try to explain the basic concepts of Constructors in C# with Examples. I hope you enjoy this
article. Please give your feedback, suggestions, and questions about this article in the comment section.

Types of Constructors in C# with Examples

In this article, I am going to discuss Types of Constructors in C# with Examples. Please read our
previous article where we discussed the basic concepts of Constructors in C# with Examples.

Types of Constructors in C#

There are five types of constructors available in C#, they are as follows

1. Default or Parameter Less Constructor


2. Parameterized Constructor
3. Copy Constructor
4. Static Constructor
5. Private Constructor
Let’s discuss each of these constructors in detail with examples.

Default or Parameterless Constructors in C#

If a constructor method does not take any parameters, then we call that a Default or Parameter Less
Constructor. These constructors can be defined by a programmer explicitly or else will be defined implicitly
provided there is no explicit constructor under the class. So, the Default or Parameterless Constructors are
again classified into two types. They are as follows:

1. System-Defined Default Constructor


2. User-Defined Default Constructor
What is System Defined Default or Parameterless Constructor in C#?

As a programmer, if we are not defined any constructor explicitly in our program, then by default the
compiler will provide one constructor at the time of compilation. That constructor is called a default

16
constructor and the default constructor is parameterless. The default constructor will assign default values
to the data members (non-static variables). As this constructor is created by the system this is also called a
system-defined default constructor.

Example to understand System-Defined Implicit or Default Constructor in C#:

In the below example, within the Employee class, we have created a few variables. And then from the
Main method, we created an instance of the Employee class and then printed the values of the variables.

using System;
namespace ConstructorDemo
{
class Employee
{
public int Id, Age;
public string Address, Name;
public bool IsPermanent;
}
class Test
{
static void Main(string[] args)
{
Employee e1 = new Employee();
Console.WriteLine("Employee Id is: " + e1.Id);
Console.WriteLine("Employee Name is: " + e1.Name);
Console.WriteLine("Employee Age is: " + e1.Age);
Console.WriteLine("Employee Address is: " + e1.Address);
Console.WriteLine("Is Employee Permanent: " + e1.IsPermanent);
Console.ReadKey();
}
}
}
So, when you run the above code, you will see that default values based on the variable type are being
printed on the console as shown in the below image. For numeric (in our example Id and Age), the default
is 0. For string (in our example Address and Name) or object, the default value will be null (in this case
nothing will be printed on the console) and for Boolean (in our example IsPermanent), the default value is
false.

In our example, we have not specified these default values. Then who provided these default values and
when? These default values are provided by the default constructor based on the variable data type and
the compiler will provide the default constructor at the time of compilation. So, the Employee class will be
converted as follows after compilation.

17
As you can see the Implicit Constructor which is always public and parameterless initialize the variables
with default values and these default values you are seeing in the output. As this Implicit Constructor
initializes the variables with default values, we also called this a System Defined Default Constructor.

Note: The point that you need to keep in mind is that the Compiler will only provide the default constructor
if as a programmer we are not defined any constructor explicitly.

When do we need to provide the Constructor Explicitly?

If we want to execute some custom logic at the time of object creation, that logic may be object
initialization logic or some other useful logic, then as a developer, we must provide the constructor
explicitly in C#.

What is a User-Defined Default Constructor in C#?

The constructor which is defined by the user without any parameter is called the user-defined default
constructor. This constructor does not accept any argument but as part of the constructor body, you can
write your own logic.

Example to understand User-defined Default Constructor in C#

In the below example, within the Employee class, we have created a public parameterless constructor
which is used to initialize the variables with some default hard-coded values. And then from the Main
method, we created an instance of the Employee class and invoke the Display method.

using System;
namespace ConstructorDemo
{
class Employee
{
public int Id, Age;
public string Address, Name;
public bool IsPermanent;
//User Defined Default Constructor
public Employee()
{
Id = 100;
Age = 30;
Address = "Bhubaneswar";
Name = "Anurag";
IsPermanent = true;
}

18
public void Display()
{
Console.WriteLine("Employee Id is: " + Id);
Console.WriteLine("Employee Age is: " + Age);
Console.WriteLine("Employee Address is: " + Address);
Console.WriteLine("Employee Name is: " + Name);
Console.WriteLine("Is Employee Permanent: " + IsPermanent);
}
}
class Program
{
static void Main(string[] args)
{
Employee e1 = new Employee();
e1.Display();
Console.ReadKey();
}
}
}
Output:

The Employee class constructor is also called a Default Constructor because it is public and parameter-
less.

And more importantly, it does not matter how many objects are being created for the Employee class, each
instance or object is initialized with the same set of values. This is the reason we call it a Default
Constrictor. As this constructor is created by the user, so we call it a User-Defined Default Constructor.

The drawback of the above user-defined default constructor is that each and every instance (i.e. object) of
the class will be initialized (assigned) with the same set of values. That means it is not possible to initialize
each instance of the class with different values. For a better understanding, please modify the Main
method as follows and see the output.

class Program
{
static void Main(string[] args)

19
{
Employee e1 = new Employee();
e1.Display();
Employee e2 = new Employee();
Console.WriteLine();
e2.Display();
Console.ReadKey();
}
}
Output:

When should we define a parameterized constructor in a class?

If we want to initialize the object dynamically with the user-given values or if we want to initialize each
instance of a class with a different set of values then we need to use the Parameterized Constructor in C#.
The advantage is that we can initialize each instance with different values.

What is Parameterized Constructor in C#?

If a constructor method is defined with parameters, we call it a Parameterized Constructor in C#, and these
constructors are defined by the programmers only but never can be defined implicitly. So, in simple words,
we can say that the developer-given constructor with parameters is called Parameterized Constructor in
C#.

Let us understand Parameterized Constructor in C# with Examples. Please have a look at the below code.
Here, we have a class called ParameterizedConstructor, and this class has one constructor which is taking
one integer parameter. As this constructor takes a parameter, we call it a Parameterized Constructor. And
in this constructor, we are printing the i value.

And now, when you are going to create an instance of the ParameterizedConstructor class, it will ask you
for the integer parameter value as shown in the below image.

20
Now, you can pass an integer value. Suppose, we pass the value 10, then that value 10 will directly come
to variable i which is then printed on the console. For a better understanding, please have a look at the
below image.

The complete example code is given below.

using System;
namespace ConstructorDemo
{
class Program
{
static void Main(string[] args)
{
ParameterizedConstructor obj = new ParameterizedConstructor(10);
Console.ReadKey();
}
}
public class ParameterizedConstructor
{
public ParameterizedConstructor(int i)
{
Console.WriteLine($"Parameterized Constructor is Called: {i}");
}
}
}
Output: Parameterized Constructor is Called: 10

So, in this way, we can create any number of instances of the class, and while creating the instance we
can pass different values and those values will go and sit in the variable i. In the below example, we are
creating two different instances of ParameterizedConstructor class with two different values.

using System;
namespace ConstructorDemo
{
class Program
{
static void Main(string[] args)
{
ParameterizedConstructor obj1 = new ParameterizedConstructor(10);
ParameterizedConstructor obj2 = new ParameterizedConstructor(20);
Console.ReadKey();

21
}
}
public class ParameterizedConstructor
{
public ParameterizedConstructor(int i)
{
Console.WriteLine($"Parameterized Constructor is Called : {i}");
}
}
}
Output:

When should we use Parameterized Constructor in C#?

With the help of a Parameterized constructor, we can initialize each instance of the class with a different
set of values. That means using parameterized constructor we can store a different set of values in
different instances created in the class.

Let us understand this with an example. Please have a look at the below class. This is the same class that
we worked on in our previous example with some changes. Now, in the class, I have declared a variable
called x. Remember, this variable x is initialized with default value only i.e. 0. Why default value? Because
we didn’t assign a value and when we don’t assign a value, the constructor will take the responsibility of
assigning a value. And the value for x is going to be 0. Then we created a method called Display where we
print the x value.

Advertisements
AD

Now, let us call this Display method using two different instances. The complete example code is given
below.

using System;
namespace ConstructorDemo
{
class Program
{
static void Main(string[] args)
{
ParameterizedConstructor obj1 = new ParameterizedConstructor(10);
obj1.Display();
ParameterizedConstructor obj2 = new ParameterizedConstructor(20);
obj2.Display();
Console.ReadKey();
}
}
public class ParameterizedConstructor

22
{
int x;
public ParameterizedConstructor(int i)
{
Console.WriteLine($"Parameterized Constructor is Called : {i}");
}
public void Display()
{
Console.WriteLine($"Value of X = {x}");
}
}
}
Output:

As you can see in the above image, for both the instances it is printing the x value as 0. In instance one we
pass 10 to the constructor and in instance two we pass 20 to the constructor. So, can we use the values
10 and 20 in place of x? Yes, it is possible. How it is possible? By using Parameterized constructor only.
Let us see how we can do this. Inside the constructor, we can assign the x variable with the value of I as
shown in the below image.

With the above changes in place, now if you run the application, then it will print 10 and 20 for the x
variable. The complete example code is given below.

using System;
namespace ConstructorDemo
{
class Program
{
static void Main(string[] args)
{
ParameterizedConstructor obj1 = new ParameterizedConstructor(10);
obj1.Display();
ParameterizedConstructor obj2 = new ParameterizedConstructor(20);
obj2.Display();
Console.ReadKey();
}
}
public class ParameterizedConstructor
{
int x;
public ParameterizedConstructor(int i)
{
//Initializing the variable
x = i;

23
Console.WriteLine($"Parameterized Constructor is Called : {i}");
}
public void Display()
{
Console.WriteLine($"Value of X = {x}");
}
}
}
Output:

As we have created two instances separately i.e. obj1 and obj2. So, internally two copies of the x variable
are available in the memory for us. For a better understanding, please have a look at the below diagram.
As you can see in the below image, we have two separate objects i.e. obj1 and obj2. For obj1 we have one
copy of the x variable with the value 10 is there and the obj2 another copy of the x variable with the value
20 is there in the memory.

Advertisements
AD

Copy Constructor in C#:

If we want to create multiple instances with the same values then we need to use the copy constructor in
C#, in a copy constructor the constructor takes the same class as a parameter to it.

Let us understand Copy Constructor in C# with Examples. Please have a look at the below code. This is
the same code that we have written in our previous example.

using System;
namespace ConstructorDemo
{
class Program
{
static void Main(string[] args)
{
CopyConstructor obj1 = new CopyConstructor(10);
obj1.Display();
Console.ReadKey();
}
}
public class CopyConstructor
{
int x;
public CopyConstructor(int i)
{
x = i;
}
public void Display()

24
{
Console.WriteLine($"Value of X = {x}");
}
}
}
Output: Value of X = 10

Now, I want to create another instance with the same value. Then I can create another instance as follows.

See, passing one parameter is not a difficult task. Suppose, the constructor takes 10 or 20 parameters,
then it is a time-consuming and error-prone process to pass the same 10 or 20 parameters. We can
overcome this problem by using Copy Constructor in C#. The copy constructor takes a parameter of the
same class type. How we can pass a class name as a parameter. This is because a class is a user-
defined data type. For a better understanding, please have a look at the below image.

With the above changes, now you can see we have two constructors as shown in the below image. One
constructor takes an int as a parameter and the other constructor takes the CopyConstructor type as a
parameter.

25
So, can we define multiple constructors in a class? Yes, we can. Constructors can be overloaded in C#.
The complete example code is given below. Now, we are passing obj1 as a parameter to the copy
constructor.

using System;
namespace ConstructorDemo
{
class Program
{
static void Main(string[] args)
{
CopyConstructor obj1 = new CopyConstructor(10);
obj1.Display();
CopyConstructor obj2 = new CopyConstructor(obj1);
obj2.Display();
Console.ReadKey();
}
}
public class CopyConstructor
{
int x;
//Parameterized Constructor
public CopyConstructor(int i)
{
x = i;
}
//Copy Constructor
public CopyConstructor(CopyConstructor obj)
{
x = obj.x;
}
public void Display()
{
Console.WriteLine($"Value of X = {x}");
}
}
}
Now, if you run the application then you see that both the instances will have the same x value as shown in
the below image,

Now, the memory is separate for each instance but the value is going to be the same for both instances.
For a better understanding, please have a look at the below diagram.

How many Constructors can be Defined in a Class in C#?

In C#, within a class, we can define any number of constructors. But the most important point that you
need to remember is that each and every constructor must have a different signature. A different signature

26
means the number, type, and parameter order should be different. So, in a class, we can define one no-
argument constructor plus ‘n’ number of parameterized constructors in C#.

Static Constructor in C#

In C#, it is also possible to create a constructor as static and when we do so, it is called a Static
Constructor. If a constructor is declared explicitly by using the static modifier, then it is called a static
constructor in C#. All the constructors we defined till now are non-static or instance constructors.

For a better understanding, please have a look at the below example. In a static constructor, you cannot
use any access specifiers like public, private, and protected.

But, when you will compile the above, the compiler will provide the default parameter less constructor. For
a better understanding, please have a look at the below code.

Points to Remember while working with Static Constructors in C#:

Point1:

If a class contains any static variables, then only implicit static constructors come into the picture otherwise
we must be defined them explicitly. On the other hand, non-static constructors will be implicitly defined in
every class (except the static class) provided we didn’t define any constructor explicitly.

Point2:

Static Constructors are responsible for initializing static variables and these constructors are never called
explicitly. They are called Implicitly and moreover, these constructors are the first to execute in any
class. For a better understanding, please have a look at the below example. Here, we have defined one
static constructor, and please observe from the Main method we are not calling the Static constructor.

using System;
namespace ConstructorDemo
{
public class StaticConstructor
{
static StaticConstructor()
{
Console.WriteLine("Static Constructor Executed!");
}
static void Main(string[] args)

27
{
Console.WriteLine("Main Method Exceution Started...");
Console.ReadKey();
}
}
}
Now, when you execute the above code, the Static constructor will execute first and then the main method.
And this proves the following output.

The non-static constructors are never called implicitly, they are always called explicitly whereas the static
constructor never called explicitly, they are always going to be called implicitly. How does the execution
happen? See, the Main method is the starting point of execution, and in this case no difference. The
program execution will start from the Main method but before executing any statement inside the Main
method, it will first execute the Static constructor and once the Static Constructor execution is completed,
then it will continue the execution of the Main method. So, the static constructor is the first block of code in
a class to be executed.

Point3:

Static Constructors cannot be parameterized, so overloading of the static constructors is not possible in
C#. Now, the question is why we cannot parameterize the static constructor? The answer is simple. The
static constructors are executed implicitly and hence we never get a chance to pass a value. And as the
static constrictor is the first block to be executed in a class, and hence there is no chance to pass a value.

Points To Remember About Static Constructor in C#:

1.There can be only one static constructor in a class.


2.It can’t be called explicitly, it is always called implicitly.
3.The static constructor should be without any parameters.
4.It can only access the static members of the class.
5.There should not be any access specifiers in the static constructor definition.
6.If a class is static then we cannot create the object for the static class.
7.It is called automatically to initialize the static members.
8.Static constructor will be invoked only once i.e. at the time of class loading.
Can we initialize non-static data members within a static constructor in C#?

It is not possible to initialize non-static data members within a static constructor, it raises a compilation
error. For a better understanding, please have a look at the following example.

Can we initialize static data fields within a non-static constructor in C#?

Yes, we can initialize static data members within a non-static constructor. Consider the following example
for better understanding:

28
What is a Private Constructor in C#?

In C#, it is also possible to create a constructor as private. The constructor whose accessibility is private is
known as a private constructor. When a class contains a private constructor then we cannot create an
object for the class outside of the class. So, private constructors are used to create an object for the class
within the same class. Generally, private constructors are used in the Remoting concept.

Example to understand Private Constructor in C#

using System;
namespace ConstructorDemo
{
class Program
{
private Program()
{
Console.WriteLine("This is private constructor");
}
static void Main(string[] args)
{
Program p = new Program();
Console.WriteLine("Main method");
Console.ReadKey();
}
}
}
Points To Remember about C# Private Constructor:

1. Using Private Constructor in C# we can implement the singleton design pattern.


2. We need to use the private constructor in C# when the class contains only static members.
3. Using a private constructor is not possible to create an instance from outside the class.
In the next article, I am going to discuss Why Do We Need Constructors in C# with Examples. Here, in
this article, I try to explain the Types of Constructors in C# with Examples. I hope you enjoy this Types of
Constructors in C# article. Please give your feedback, suggestions, and questions about this article in the
comment section.

Why We Need Constructors in C#?

In this article, I am going to discuss Why We Need Constructors in C# with Real-time Examples. This is
our Part-3 of Constructors. In Part-1 we discussed what exactly a constructor is and in Part-2 we
discussed the different types of constructors in C#. In this part, I will demonstrate to you why we need
constructors in our class.

Why do we need Constructors in C#?

Every class requires a constructor to be present in it if we want to create the instance of that class. Every
class contains an implicit constructor if not defined explicitly by the programmer and with the help of that
implicit constructor, we can create the instance of that class.

29
If we don’t define any constructors, then an implicit constructor is there which is provided by the compiler
at the time of compilation and using that implicit constructor we can create the instance, then the question
is why do we need to define the constructor explicitly again or when do we need to define an explicit
constructor in C#?

What is the need of Defining a Constructor Explicitly Again?

This is one of the frequently asked interview questions. Let us understand this. Implicit Constructors of a
class will initialize variables of a class with the same value even if we create multiple instances of that
class.

Let us understand this with an example. Please have a look at the following code. Here, we have a class
called First with one variable and then from inside the Main method, we are creating three instances of the
First class.

using System;
namespace ConstructorDemo
{
class First
{
public int x = 100;
}
class Test
{
static void Main(string[] args)
{
First f1 = new First();
First f2 = new First();
First f3 = new First();
Console.WriteLine($"{f1.x} {f2.x} {f3.x}");
Console.ReadKey();
}
}
}
Output: 100 100 100

Now, internally, it allocates the memory separately for each instance as shown in the below image. The
point that you need to remember, we created three instances and these three instances have a copy of x.
And the value is going to be the same for all.

This is the problem. Right now, the class contains a constructor i.e. Implicit constructor. And that
constructor is going to initialize the variable x with the value 100. So, how many instances we are going to
be created, all the instances will be created with the same value.

30
If we define constructors explicitly with parameters then we will get a chance of initializing the fields or
variables of the class with a new value every time we are going to create the instance of that class.

Now, observe the below example, here we have created another class called Second, and this class has a
variable called x. Now, the implicit constructor will initialize the x variable with the default value 0 when we
created an instance of the Second class and the same for each instance.

using System;
namespace ConstructorDemo
{
class First
{
public int x = 100;
}
class Second
{
//Initialize with default value
public int x;
}
class Test
{
static void Main(string[] args)
{
First f1 = new First();
First f2 = new First();
First f3 = new First();
Console.WriteLine($"{f1.x} {f2.x} {f3.x}");
Second s1 = new Second();
Second s2 = new Second();
Second s3 = new Second();
Console.WriteLine($"{s1.x} {s2.x} {s3.x}");
Console.ReadKey();
}
}
}
Output:

Now, I want the x value to be different under the three instances. What value I don’t know, I will come to
know the value when I am going to create the instances. Remember one thing whenever we are creating a
class means we can reuse the class and we can create the instance whenever and wherever we want.
That is code reusability.

So, in the future whenever I am going to create an instance of the class Second, I only need to send the
value for x. This is the scenario where we need to go for or defined an explicit parameterized constructor.
Let us modify the Second class as follows to add one explicit parameterized constructor to initialize the x
variable.

31
Here, this.x refers to the class variable x. See, when I select this.x, automatically the class variable x is
highlighted as shown in the below image.

And here x refers to the local variable x. See, when I select x, automatically the local variable x is
highlighted as shown in the below image.

This means the local variable x is being assigned to the class variable x. Now, while creating the instance
of the Second class, we need to pass a value and that value is stored inside the local variable x. And in
this way, while creating multiple instances of the class Second, we can pass different, different values as
shown in the below image.

The complete example code is given below.

using System;
namespace ConstructorDemo
{
class First
{
public int x = 100;
}
class Second
{
public int x;
//Parameterized Explicit Constructor
public Second(int x)

32
{
this.x = x;
}
}
class Test
{
static void Main(string[] args)
{
First f1 = new First();
First f2 = new First();
First f3 = new First();
Console.WriteLine($"{f1.x} {f2.x} {f3.x}");
Second s1 = new Second(100); //100 wll send to local variable x
Second s2 = new Second(200); //200 wll send to local variable x
Second s3 = new Second(300); //300 wll send to local variable x
Console.WriteLine($"{s1.x} {s2.x} {s3.x}");
Console.ReadKey();
}
}
}
Output:

The following diagram shows the memory architecture of the above example. Here, for the First class, all
the instances contain the same value for x. On the other hand, for class Second, all the instances have a
different value and this is possible because of the Explicit Parameterized Constructor in C#.

When we define a class, first identify whether the class variables require some values to execute and if
they are required then define a constructor explicitly and pass values through the constructor, so that every
time the instance of the class is created, we get a chance of passing new values.

Note: Generally, every class requires some values for execution, and the values that are required for a
class to execute are always sent to that class by using the constructor only.

Parameterized Constructor Real-time Example in C#

With the help of a Parameterized constructor, we can initialize each instance of the class with a different
set of values. That means using parameterized constructor we can store a different set of values in
different objects created in the class. For a better understanding, please have a look at the below example.

using System;
namespace ConstructorDemo
{
class Employee
{

33
public int Id, Age;
public string Address, Name;
public bool IsPermanent;
//User Defined Parameterized Constructor
public Employee(int id, int age, string name, string address, bool isPermanent)
{
Id = id;
Age = age;
Address = address;
Name = name;
IsPermanent = isPermanent;
}
public void Display()
{
Console.WriteLine("Employee Id is: " + Id);
Console.WriteLine("Employee Name is: " + Age);
Console.WriteLine("Employee Address is: " + Address);
Console.WriteLine("Employee Name is: " + Name);
Console.WriteLine("Is Employee Permanent: " + IsPermanent);
}
}
class Program
{
static void Main(string[] args)
{
Employee e1 = new Employee(101, 30, "Pranaya", "Mumbai", true);
e1.Display();
Console.WriteLine();
Employee e2 = new Employee(101, 28, "Rout", "BBSR", false);
e2.Display();
Console.ReadKey();
}
}
}
Output:

Copy Constructor Real-time Example in C#

The constructor which takes a parameter of the class type is called a copy constructor. This constructor is
used to copy one object’s data into another object. The main purpose of the copy constructor is to initialize
a new object (instance) with the values of an existing object (instance). For a better understanding, please
have a look at the below example.

using System;
namespace ConstructorDemo
{
class Employee
{
public int Id, Age;
public string Address, Name;
public bool IsPermanent;

34
//Parameterized Constructor
public Employee(int id, int age, string name, string address, bool isPermanent)
{
Id = id;
Age = age;
Address = address;
Name = name;
IsPermanent = isPermanent;
}
//Copy Constructor
public Employee(Employee emp)
{
Id = emp.Id;
Age = emp.Age;
Address = emp.Address;
Name = emp.Name;
IsPermanent = emp.IsPermanent;
}
public void Display()
{
Console.WriteLine("Employee Id is: " + Id);
Console.WriteLine("Employee Name is: " + Age);
Console.WriteLine("Employee Address is: " + Address);
Console.WriteLine("Employee Name is: " + Name);
Console.WriteLine("Is Employee Permanent: " + IsPermanent);
}
}
class Program
{
static void Main(string[] args)
{
Employee e1 = new Employee(101, 30, "Pranaya", "Mumbai", true);
e1.Display();
Console.WriteLine();
Employee e2 = new Employee(e1);
e2.Display();
Console.ReadKey();
}
}
}
Output:

Static Constructor Real-time Example in C#

The static Constructor in C# will be invoked only once. There is no matter how many instances (objects) of
the class are created, it is going to be invoked only once and that is when the class is loaded for the first
time.

The static constructor is used to initialize the static fields of the class. You can also write some code inside
the static constructor which is going to be executed only once. The static data members in C# are created
only once even though we created any number of objects.

35
using System;
namespace StaticConstructorDemo
{
class Example
{
int i;
static int j;
//Default Constructor
public Example()
{
Console.WriteLine("Default Constructor Executed");
i = 100;
}
//static Constructor
static Example()
{
Console.WriteLine("Static Constructor Executed");
j = 100;
}
public void Increment()
{
i++;
j++;
}
public void Display()
{
Console.WriteLine("Value of i : " + i);
Console.WriteLine("Value of j : " + j);
}
}
class Test
{
static void Main(string[] args)
{
Example e1 = new Example();
e1.Increment();
e1.Display();
e1.Increment();
e1.Display();
Example e2 = new Example();
e2.Increment();
e2.Display();
e2.Increment();
e2.Display();
Console.ReadKey();
}
}
}
Output:

36
In the next article, I am going to discuss Static vs Non-Static Constructors in C# with Examples. Here,
in this article, I try to explain Why Do we Need Constructors in C# with Examples. I hope you enjoy this
Why Do We Need Constructors in C# with Real-time Examples article. Please give your feedback,
suggestions, and questions about this article in the comment section.

Static vs Non-Static Constructors in C# with Examples

In this article, I am going to discuss Static vs Non-Static Constructors in C# with Examples. Please read
our previous article, where we discussed Why We Need Constructors in C# with Examples.

Static vs Non-Static Constructors in C#

Point1:

If a constructor is explicitly declared by using the static modifier, we call that constructor a static
constructor whereas the rest of the others are called non-static constructors only. For a better
understanding, please have a look at the below code. Non-Static Constructors are also called Instance
Constructors in C#.

Point2:

Constructors are responsible for initializing the fields or variables of a class. Static Fields/Variables are
initialized by static constructors and non-static fields/variables are initialized by non-static or instance
constructors in C#. For a better understanding, please have a look at the below code. Here, both the
variables x and y are initialized with the default value i.e. 0. The variable x is going to be initialized by a
static constructor whereas the variable y is going to be initialized by a non-static constructor.

Point3:

Static constructors are implicitly called whereas non-static constructors are explicitly called. For better
understanding, please have a look at the below example. Here, the Program execution is always going to
start from the Main method. In the below example, the Main method and Static constructors, both are
present in the same classes. So, before executing the body of the Main method, it will execute the static
constructor of the class because the static constructor is the first block of code to be executed under a

37
class and once the static constructor execution is completed, then it will execute the Main method body.
So, when you will run the below code, you will see that first, the static constructor is executed and then
only the Main method is executed.

using System;
namespace ConstructorDemo
{
public class ConstructorsDemo
{
static int x; //It is going to be initialized by static constructor
int y; //It is going to be initialized by non-static constructor
//Static Constructor
static ConstructorsDemo()
{
//This constructor initialized the static variable x with default value i.e. 0
Console.WriteLine("Static Constructor is Called");
}
//Non-Static Constructor
public ConstructorsDemo()
{
//This constructor initialized the static variable y with default value i.e. 0
Console.WriteLine("Non-Static Constructor is Called");
}
//Main Method is the Entry Point for our Application Execution
static void Main(string[] args)
{
//Before Executing the body of Main Method, Static Constructor is executed
Console.WriteLine("Main Method Body..");
Console.ReadKey();
}
}
}
Output:

If you notice, we did not call the Static Constructor anywhere in our code, but it is executed. That means, it
is always going to be called Implicitly. In the above example, we have not called the no-static constructors,
and hence the non-static constructor is not executed.

Point4:

Static Constructors execute immediately once the execution of a class start and moreover, it is the first
block of code to run under a class whereas non-static constructors execute only after creating the instance
of the class as well as each and every time the instance of the class is created.

For a better understanding, please have a look at the below example. In the below example, the Main
method and Static constructors are present in two different classes. So, the Program execution started
from the Main method and it will start executing the Main method body. Then inside the Main method, we
are creating the instance of ConstructorsDemo class i.e. we are trying to execute ConstructorsDemo class
for the first time and as this class has a static constructor, that static constructor will implicitly be called and
once that static constructor completes its execution, then only the instance is being created and the non-
static constructor is executed.

using System;
namespace ConstructorDemo
{
class Program
{
//Main Method is the Entry Point for our Application Execution
static void Main(string[] args)
{

38
Console.WriteLine("Main Method Started");
//Creating Object of ConstructorsDemo
//Now the ConstructorsDemo class Execution Start
//First, it will execute the Static constructor
//Then it will execute the non-static constructor
ConstructorsDemo obj = new ConstructorsDemo();
Console.WriteLine("Main Method Completed");
Console.ReadKey();
}
}
public class ConstructorsDemo
{
static int x; //It is going to be initialized by static constructor
int y; //It is going to be initialized by non-static constructor
//Static Constructor
static ConstructorsDemo()
{
//This constructor initialized the static variable x with default value i.e. 0
Console.WriteLine("Static Constructor is Called");
}
//Non-Static Constructor
public ConstructorsDemo()
{
//This constructor initialized the static variable y with default value i.e. 0
Console.WriteLine("Non-Static Constructor is Called");
}
}
}
Output:

In the above example, the execution takes place as follows:

1. First, the Main method of the Program class starts its execution as it is the entry point for our
application.
2. Then the Static Constructor of the ConstructorsDemo class is executed.
3. Then the Non-Static Constructor of the ConstructorsDemo class is executed.
4. Finally, the Main method completes its execution.
Point5:

Static Constructors are executed only once whereas the non-static constructors are executed 0 or n
number of times depending on the number of instances we created for the class. For a better
understanding, please have a look at the below example. In the below example, the place where we try to
invoke the static variable using the class name ConstructorsDemo, first it will invoke the static constructor
implicitly. As we are not creating an instance for the ConstructorsDemo class, the non-static constructor is
not going to be executed.

using System;
namespace ConstructorDemo
{
class Program
{
//Main Method is the Entry Point for our Application Execution
static void Main(string[] args)
{
Console.WriteLine("Main Method Started");
//As soon as it finds ConstructorsDemo.x,
//it will first execute the static constructor of the class
Console.WriteLine(ConstructorsDemo.x);

39
Console.WriteLine("Main Method Completed");
Console.ReadKey();
}
}
public class ConstructorsDemo
{
public static int x; //It is going to be initialized by static constructor
public int y; //It is going to be initialized by non-static constructor
//Static Constructor
static ConstructorsDemo()
{
//This constructor initialized the static variable x with default value i.e. 0
Console.WriteLine("Static Constructor is Called");
}
//Non-Static Constructor
public ConstructorsDemo()
{
//This constructor initialized the static variable y with default value i.e. 0
Console.WriteLine("Non-Static Constructor is Called");
}
}
}
Output:

Now, please have a look at the below example. Here, we are creating 3 instances of the
ConstructorsDemo class. In this case, when we create the first instance, before executing the non-static
constructor, it will execute the static constructor first. Once the static constructor is executed, then the non-
static constructor starts executing. This happens only for the first instance of creation time. From the
second instance creation, the static constructor is not going to be executed. So, when you will run the
above code, you will see that the static constructor is executed only once and the non-static constructor is
executed three times.

using System;
namespace ConstructorDemo
{
class Program
{
//Main Method is the Entry Point for our Application Execution
static void Main(string[] args)
{
Console.WriteLine("Main Method Started");
//Before Executing the non-static constructor
//it will first execute the static constructor of the class
ConstructorsDemo obj1 = new ConstructorsDemo();
//Now, onwards it will not execute the static constructor,
//Because static constructor executed only once
ConstructorsDemo obj2 = new ConstructorsDemo();
ConstructorsDemo obj3 = new ConstructorsDemo();
Console.WriteLine("Main Method Completed");
Console.ReadKey();
}
}
public class ConstructorsDemo
{
public static int x; //It is going to be initialized by static constructor
public int y; //It is going to be initialized by non-static constructor
//Static Constructor

40
static ConstructorsDemo()
{
//This constructor initialized the static variable x with default value i.e. 0
Console.WriteLine("Static Constructor is Called");
}
//Non-Static Constructor
public ConstructorsDemo()
{
//This constructor initialized the static variable y with default value i.e. 0
Console.WriteLine("Non-Static Constructor is Called");
}
}
}
Output:

When the Static Constructor of a Class is Executed in C#?

It is very important for us to understand when the static constructor of a class is executed implicitly. The
following are the three scenarios where the static constructor is executed implicitly.

1. If both the static constructor and Main method are present in a single class, then the program
execution will start from the Main method, but before executing the Main method body, it will first
execute the Static Constructor of the class.
2. When we call any static variables or static methods for the First time in a class, then it will execute the
static constructor of that class.
3. When we create an instance of a class for the first time, then before executing the non-static
constructor, it will first execute the static constructor of that class.
The most important point that you need to remember is static constructors are executed only once
irrespective of the number of times you called the static variables or static methods or irrespective of the
number of times you created the instance of the class.

Note: In the life cycle of a class (life cycle in the sense the moment we start the execution to the end of the
class is considered as one life cycle), the static constructor is executed once and only one time whereas
the non-static constructors execute for 0 times if no instances are created and n times if n number of
instances are created.

Point6:

Non-Static Constructors can be parameterized whereas the static constructors cannot have any
parameter. This is because we explicitly call the non-static constructors, so we can have a chance to pass
parameters. On the other hand, static constructors are implicitly called and it is the first block of code to run
under a class, and hence we don’t have any chance to pass parameters. For a better understanding,
please have a look at the below code. So, a static constructor must be parameterless in C#.

41
Point7:

Non-Static Constructors can be overloaded whereas static constructors cannot be overloaded.


Overloading is something that comes into the picture based on the parameters. As we have a chance to
pass parameters in the case of non-static constructors, overloading is possible. On the other hand, we
cannot pass parameters to static constructors i.e. static constructors are parameterless, and hence
overloading is not possible. For a better understanding, please have a look at the below code.

42
Point8:

Every class contains an implicit constructor if not defined explicitly and those implicit constructors are
defined based on the following criteria.

1. Every class except a static class contains an implicit non-static constructor if not defined with an
explicit constructor.
2. Static constructors are implicitly defined only if that class contains any static fields or else that
constructor will not be present provided that the class does not have an explicit static constructor.
Summary of Static and Non-Static Constructors:

1. A constructor is a special method inside a class used to initialize the data members. If we create the
constructor using a static modifier then we call it a static constructor and the rest of all are non-static
constructors only.
2. The static constructor is used to initialize the static data members and the non-static constructor is
used to initialize the non-static data members of a class.
3. The static constructor is always invoked implicitly while the non-static constructor is always invoked
explicitly.
4. If we have not defined any constructor explicitly, then the compiler will provide the implicit constructor
in the following conditions.
5. For a static class, the compiler will provide a static constructor implicitly, but no non-static constructor.
6. For a non-static class, the compiler will provide a non-static constructor, if the non-static class has
any static member, then only the compiler will provide the static constructor.
7. Static constructors will execute only once during the life cycle of a class and non-static constructors
are executed 0 or n number times. If we have not created any object, then the constructor will execute
0 times and if we create n number of objects, then the constructor will execute n number of times.
8. In a class, we can have only one static constructor and i.e. too parameterless, and hence static
constructor cannot be overloaded. But, in a class, we can define any number of non-static
constructors and hence non-static constructors as overloaded.
9. A static constructor is executed when our class execution starts and it will execute only once and it
will be the first block inside a class to be executed while non-static constructors are going to be
executed when we create an instance of a class and for each instance of the class.
So, these are all the differences between static and non-static constructors in C#. To learn more about
constructors, please see the following.

Constructors in C#
Type of Constructors in C#
How to use Constructors in Real-time Application Development using C#

In the next article, I am going to discuss Private Constructors in C# with Examples. Here, in this article, I
try to explain Static vs Non-Static Constructors in C# with Examples. I hope you enjoy this Static vs
Non-Static Constructors in C# with Examples article. Please give your feedback, suggestions, and
questions about this Static vs Non-Static Constructors in C# article in the comment section.

Private Constructors in C# with Examples

In this article, I am going to discuss Private Constructors in C# with Examples. I got many emails,
messages, and comments to make an article related to Private Constructors in C#. There are a lot of
confusion and doubts regarding private constructors among the developers and I hope at the end of this
article, all your doubts and confusions will be cleared.

What is a Private Constructor in C#?

In C#, when the constructor is created by using the Private Access Specifier, then it is called a Private
Constructor. When a class contains a private constructor and if the class does not have any other
Public Constructors, then you cannot create an object for the class outside of the class. But we
can create objects for the class within the same class.

So, the most important point that we need to keep in mind is that the restrictions such as restrictions for
creating objects, restrictions for accessing members, etc. will come into the picture when you are trying to
create the objects and accessing the members from outside the class. If you are creating the objects and
accessing the members within the same class, then no such restrictions come into the picture.

Creating Object using Private Constructor within the same class in C#:

43
Many articles on the web say that you cannot create an instance of the class if it has a private constructor.
But this is partially true. You cannot create an instance from outside the class, but you can create the
instance from within the class. For a better understanding, please have a look at the below example. Here,
in the Program class, we defined a private constructor and the Main method is also defined in the same
Program class. As you can see, within the Main method, we are creating an instance of the Program class
and calling the Method1.

using System;
namespace PrivateConstructorDemo
{
class Program
{
//Private Constructor
private Program()
{
Console.WriteLine("This is Private Constructor");
}
public void Method1()
{
Console.WriteLine("Method1 is Called");
}
static void Main(string[] args)
{
//Creating instance of Program class using Private Constructor
Program obj = new Program();
obj.Method1();
Console.ReadKey();
}
}
}
Output:

Creating an Instance from Outside the Class in C#:

The point that you need to remember is while creating the instance from outside the class, the class should
have a public constructor. It does not matter if a class has a private constructor or not, but if a class has a
public constructor, then using that public constructor, we can create the class instance and invoke the
public non-static members.

For a better understanding, please have a look at the below example. Here, we have the Test class with
both Private and Public constructors and a public method. Now, from the Program class Main method
(which is outside of the Test class), we are creating an instance of the Test class and invoking the
Methdo1.

using System;
namespace PrivateConstructorDemo
{
class Program
{
static void Main(string[] args)
{
//Creating instance of Test class using public Constructor
Test obj = new Test(10);
obj.Method1();
Console.ReadKey();
}
}
public class Test
{

44
//Private Constructor
private Test()
{
Console.WriteLine("This is Private Constructor");
}
//Public Constructor
public Test(int x)
{
Console.WriteLine("This is public Constructor");
}
public void Method1()
{
Console.WriteLine("Method1 is Called");
}
}
}
Output:

Now, what happens if the class does not have any public constructor and has only a private constructor?
Then we cannot create an instance from outside the class. For a better understanding, please have a look
at the below example. Here, the Test class is having only a private constructor and from the Main method,
while creating the instance of the Test class using the Private constructor, we are getting a compile-time
error.

using System;
namespace PrivateConstructorDemo
{
class Program
{
static void Main(string[] args)
{
//Creating instance of Test class using public Constructor
Test obj = new Test();
obj.Method1();
Console.ReadKey();
}
}
public class Test
{
//Private Constructor
private Test()
{
Console.WriteLine("This is Private Constructor");
}
public void Method1()
{
Console.WriteLine("Method1 is Called");
}
}
}
Output:

As you can see here, we are getting the error ‘Test.Test()’ is inaccessible due to its protection
level and this makes sense because the Test class Test() constructor is inaccessible in the Program class
because of its protection level i.e. private.

45
Note: The first important point that you need to remember is Private constructor restricts the class to be
instantiated from outside the class only if it does not have any public constructor. If it has a public
constructor, then we can create the instance from outside of the class. There is no restriction to creating
the instance from within the same class.

Use Case: The use case of Private Constructor in C# is that if you don’t want your class to be instantiated
from outside the class, then add a private constructor without any public constructor in your class.

Private Constructor Restricting Inheritance in C#:

On many websites, you will find that they are saying Private Constructor Restricting Inheritance in C#. That
means if you have a private constructor in a class, then that class cannot be inherited. This is also partially
true. Let us prove this point with a few examples.

See, if your class has a private constructor as well as any other public constructor, then it is possible to
inherit your class. What the child class requires to establish a parent-child relationship is a publicly
accessible constructor. That means it does not matter whether your class has any private constructor or
not, if it has a public constructor, then you can inherit the class.

For a better understanding, please have a look at the following example. Here, inside the Parent class, we
have two constructors i.e. one private constructor and one public constructor. Then Child class inherits
from the Parent class and we are not getting any errors.

using System;
namespace PrivateConstructorDemo
{
class Program
{
static void Main(string[] args)
{
//Creating instance of Child class
Child obj = new Child();
Console.ReadKey();
}
}
public class Parent
{
//Private Constructor
private Parent()
{
Console.WriteLine("Parent Class Private Constructor is Called");
}
//Public Constructor
public Parent(string Message)
{
Console.WriteLine("Parent Class Public Constructor is Called");
}
}
public class Child : Parent
{
public Child() : base ("Hello")
{
Console.WriteLine("Child Class Public Constructor is Called");
}
}
}
Output:

If the Parent class has only a private constructor and does not have any public constructors then
Inheritance is not possible with outside classes. For a better understanding, please have a look at the

46
following example. Here, the Parent class has only a private constructor hence inheritance is not possible
and this time we will get a compile-time error.

using System;
namespace PrivateConstructorDemo
{
class Program
{
static void Main(string[] args)
{
//Creating instance of Child class
Child obj = new Child();
Console.ReadKey();
}
}
public class Parent
{
//Private Constructor
private Parent()
{
Console.WriteLine("Parent Class Private Constructor is Called");
}
}
public class Child : Parent
{
public Child()
{
Console.WriteLine("Child Class Public Constructor is Called");
}
}
}
Output:

Here we are getting the compile-time error and this makes sense because there is no publicly accessible
constructor in the Parent class which the Child class constructor can access.

In the above example, the Child class is from outside the Parent class and hence it is not accessible to the
Parent class private constructor. But the if the child class is an Inner class of the Parent class, then
inheritance is possible. For a better understanding, please have a look at the below example. Here, the
Child class is declared inside the Parent class and inheritance is possible.

using System;
namespace PrivateConstructorDemo
{
class Program
{
static void Main(string[] args)
{
//Creating instance of Child class
Parent.Child obj = new Parent.Child();
Console.ReadKey();
}
}
public class Parent
{
//Private Constructor
private Parent()
{

47
Console.WriteLine("Parent Class Private Constructor is Called");
}
public class Child : Parent
{
public Child()
{
Console.WriteLine("Child Class Public Constructor is Called");
}
}
}
}
Output:

If you want to restrict inheritance then don’t go for the private constructor, instead, make the Class
Sealed which will restrict the class to be inherited from either outside or inside. For a better understanding,
please have a look at the following example.

using System;
namespace PrivateConstructorDemo
{
class Program
{
static void Main(string[] args)
{
//Creating instance of Child class
Parent.Child1 obj1 = new Parent.Child1();
Child2 obj2 = new Child2();
Console.ReadKey();
}
}
public sealed class Parent
{
//Private Constructor
private Parent()
{
Console.WriteLine("Parent Class Private Constructor is Called");
}
public class Child1 : Parent
{
public Child1()
{
Console.WriteLine("Child1 Class Public Constructor is Called");
}
}
}
public class Child2 : Parent
{
public Child2()
{
Console.WriteLine("Child2 Class Public Constructor is Called");
}
}
}
Output:

48
So, we prove that the private constructor does not restrict inheritance in C#.

Use Private Constructor when your class has only Static Members in C#:

On the Internet, you will find that many peoples or articles are saying that, if your class contains only static
members, then make the class constructor private. But this is wrong. I have already shown you that even if
you have a private constructor then we can also make inheritance with inner classes and we can also
create instances within the same class.

See, the constructors either private or public are used to create the instances and initialize the non-static
variables of a class. If your class does not have any non-static members, then is there any requirement for
a constructor? The answer is No. If your class contains only static members, then it is better to make the
class static which not only restricts your class instance to be created but also it will restrict inheritance.

For a better understanding, please have a look at the below example. Here, we have a static class called
Test with two static data members. As you can see we are getting compiler time errors the Child class
trying to inherit from the Test class as well as we are also getting compile-time errors while creating the
instance of the static Test class.

using System;
namespace PrivateConstructorDemo
{
class Program
{
static void Main(string[] args)
{
//Cannot Create an instance of the Static class
Test test = new Test();
Console.ReadKey();
}
}
public static class Test
{
public static double PI = 3.14;
public static int GetSquare(int x)
{
return x * x;
}
}
//A class cannot Derive from a Static Class
public class Child: Test
{
}
}
Output:

Then you might have one question on your mind, what is the use of static class, and how we can access
the static members as we are unable to create the instance as well as unable to make the inheritance
relationship? You can access the static members of a class directly by using the class name and static
members get memory allocation only once i.e. only one copy of the static members is available and that is
too for the first time when the execution start. For a better understanding, please have a look at the below
example. Here, we are accessing the two static members using the class name Test.

using System;
namespace PrivateConstructorDemo
{

49
class Program
{
static void Main(string[] args)
{
Console.WriteLine($"PI : {Test.PI}");
Console.WriteLine($"Square of 5 : {Test.GetSquare(5)}");
Console.ReadKey();
}
}
public static class Test
{
public static double PI = 3.14;
public static int GetSquare(int x)
{
return x * x;
}
}
}
Output:

Is Private Constructor going to be Parameterless in C#?

Again, in many articles and YouTube videos, you will see that many peoples are saying private
constructors should be parameterless. But this is not true. See, in C#, constructors are overloaded. That
means we can define multiple constructors with different parameters. In overloading what is important is
the name and the parameters and it does not consider access specifiers like private, public, protected, etc
as part of the overloading. So, it is possible to define multiple private constructors in C#.

For a better understanding, please have a look at the below example. Here, in the Program class, we
define two private constructors. One private constructor is without parameters and another private
constructor is with parameters. As you can see, here we are creating two instances inside the Main
method using both the private constructors.

using System;
namespace PrivateConstructorDemo
{
class Program
{
private Program()
{
Console.WriteLine("Private Parameterless Constructor is Called");
}
private Program(string message)
{
Console.WriteLine("Private Parameterized Constructor is Called");
}
static void Main(string[] args)
{
Program obj1 = new Program();
Program obj2 = new Program("Hello");
Console.ReadKey();
}
}
}
Output:

50
When to use Private Constructors in C#?

On Internet, you will find many articles and many peoples are saying that a private constructor is used to
implement Singleton Design Pattern. Yes, absolutely right. One of the use cases of the private
constructors is to implement a singleton design pattern. Let us see how to implement a singleton design
pattern using a private constructor in C#.

What is Singleton Pattern in C#?

The Singleton Design Pattern ensures that only one instance of a particular class is going to be created
and then provide simple global access to that instance for the entire application.

How to Implement Singleton Design Pattern in C#?

The following are the steps to implement the Singleton Design Pattern in C#.

1. You need to declare only a single constructor in your class and that constructor should be private and
parameterless. This is required because it is not allowed the class to be instantiated from outside the
class. It only instantiates from within the class.
2. The class should be declared sealed which will ensure that it cannot be inherited.
3. You need to create a private static variable that is going to hold a reference to the single created
instance of the class.
4. You also need to create a public static property/method which will return the single-created instance
of the singleton class. This method or property first checks if an instance of the singleton class is
available or not. If the singleton instance is available, then it returns that singleton instance otherwise
it will create an instance and then return that instance.
Singleton Design Pattern Implementation Example in C#:

using System;
namespace PrivateConstructorDemo
{
public sealed class Singleton
{
private static int counter = 0;
private static Singleton instance = null;
private static readonly object Instancelock = new object();
public static Singleton GetSingletonInstance()
{
lock (Instancelock)
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
private Singleton()
{
counter++;
Console.WriteLine($"Singleton Constructor Executed {counter} Time");
}
public void SomeMethod(string Message)
{
Console.WriteLine($"Some Method Called : {Message}");
}
}
}
Next, modify the Main method of the Program class as follows:

using System;
namespace PrivateConstructorDemo
{

51
class Program
{
static void Main(string[] args)
{
Singleton fromPlace1 = Singleton.GetSingletonInstance();
fromPlace1.SomeMethod("From Place 1");
Singleton fromPlace2 = Singleton.GetSingletonInstance();
fromPlace2.SomeMethod("From Place 2");
Console.ReadKey();
}
}
}
Output:

If you want to learn Singleton Design Pattern in detail, please click on the below link.

https://dotnettutorials.net/lesson/singleton-design-pattern/

In the next article, I am going to discuss Destructor in C# with Examples. Here, in this article, I try to
explain Private Constructors in C# with Examples. I hope you enjoy this Private Constructor in C# with
Examples article. Please give your feedback, suggestions, and questions about Private Constructors in the
C# article in the comment section.

Destructors in C# with Examples(Read-18-April -----Revise 19-April-Rerevise-23 -April)

In this article, I am going to discuss the Destructors in C# with Examples. Please read our previous article
where we discussed the Static vs Non-Static Constructors in C# with Examples.

What are Destructors in C#?

According to MSDN, Destructors which are also called Finalizers in C# are used to perform any necessary
final clean-up when a class instance is being collected by the garbage collector.

The Destructor is also a special type of method present in a class, just like a constructor, having the same
name as the class name but prefixed with ~ tilde. The Constructor in C# is Explicitly called when the object
of the class is created. On the other hand, the Destructor in C# is Implicitly Called when the object of the
class is destroyed.

The Constructor and destructor methods will exactly have the same name as the class to which they
belong. So, to differentiate between these two, a tilde (~) symbol is used just before the destructor method.
The syntax is shown below.

52
Note: The most important point that you need to keep in mind is that a destructor method cannot have any
parameters as well as cannot be applied with any modifiers. As the destructor is not parameterized, so we
cannot overload the destructor.

When is a Destructor method Called in C#?

A destructor method gets called automatically by the garbage collector when the object of the class is
destroyed. So, the point that you need to remember is that the destructor methods are automatically called
by the garbage collector.

When will the Object of a Class get Destroyed in C#?

The object of a class in C# will be destroyed by the garbage collector in any of the following cases

1. At the end of the program execution, each and every object that is associated with the program will be
destroyed by the garbage collector.
2. The Implicit calling of the garbage collector occurs sometime in the middle of the program execution
provided the memory is full so the garbage collector will identify unused objects of the program and
destroys them.
3. The Explicit calling of the garbage collector can also be done in the middle of program execution by
the programmer with the help of the “Collect()” statement so that if there are any unused objects
associated with the program will be destroyed in the middle of the program execution.
Example to Understand Destructors in C#:

In the below example, we have created one class called DestructorDemo with one constructor and one
destructor. Then inside the Main method, we have created two instances of the DestructorDemo class and
then made the obj1 value null which is eligible for garbage collection.

using System;
namespace DestructorExample
{
class DestructorDemo
{
public DestructorDemo()
{
Console.WriteLine("Constructor Object Created");
}
~DestructorDemo()
{
string type = GetType().Name;
Console.WriteLine($"Object {type} is Destroyed");
}
}
class Program
{
static void Main(string[] args)
{
DestructorDemo obj1 = new DestructorDemo();
DestructorDemo obj2 = new DestructorDemo();
//Making obj1 for Garbage Collection
obj1 = null;
Console.ReadKey();
}
}
}
Now, when you run the above code, you will get the following output.

You can see the statements written inside the destructor are not printed in the output. Then you might be
thinking that our destructor is not executed even though we made the obj2 value null. This is not right. The
point that you need to remember is that the destructor method is implicitly called by the garbage collector

53
and we cannot predict when it calls the destructor method. And hence you cannot see those print
statements in the output. Once, the object is unused i.e. it ready for garbage collection, then it is the
responsibility of the garbage collector to destroy that unused object and free the memory from the heap.

If you want, then you can also make an explicit call to the garbage collector in the middle of the application
execution to destroy the unused object. To do so, we need to call the GC.Collect method as shown in the
below example.

using System;
namespace DestructorExample
{
class DestructorDemo
{
public DestructorDemo()
{
Console.WriteLine("Constructor Object Created");
}
~DestructorDemo()
{
string type = GetType().Name;
Console.WriteLine($"Object {type} is Destroyed");
}
}
class Program
{
static void Main(string[] args)
{
DestructorDemo obj1 = new DestructorDemo();
DestructorDemo obj2 = new DestructorDemo();
//Making obj1 for Garbage Collection
obj1 = null;
GC.Collect();
Console.ReadKey();
}
}
}
Output:

Now, you can see that the Destructor is executed once. This is because we have made the obj1 value null.
If we make both the object values null, then for each object the destructor method executes once. For a
better understanding, please have a look at the below example.

using System;
namespace DestructorExample
{
class DestructorDemo
{
public DestructorDemo()
{
Console.WriteLine("Constructor Object Created");
}
~DestructorDemo()
{
string type = GetType().Name;
Console.WriteLine($"Object {type} is Destroyed");
}
}
class Program

54
{
static void Main(string[] args)
{
DestructorDemo obj1 = new DestructorDemo();
DestructorDemo obj2 = new DestructorDemo();
//Making obj1 and obj2 ready for Garbage Collection
obj1 = null;
obj2 = null;
GC.Collect();
Console.ReadKey();
}
}
}
Output:

Can you prove the destructor method is Implicitly called by Garbage Collector?

Yes. Please have a look at the below example. In the below example, inside the Main method, we have
created an instance of the DestructorDemo class and then we are making the object null and calling the
GC.Collect methods three times. The point that you need to observe is how many times, the destructor
method or finalizer is executed and when executed.

using System;
namespace DestructorExample
{
class DestructorDemo
{
public DestructorDemo()
{
Console.WriteLine("DestructorDemo Object Created");
}
~DestructorDemo()
{
Console.WriteLine("DestructorDemo Object Destroyed");
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Main Method Execution Started");
DestructorDemo obj1 = new DestructorDemo();
//Making obj1 ready for Garbage Collection
obj1 = null;
GC.Collect();
Console.WriteLine("Some Statement Executed Inside Main Method");
obj1 = null;
GC.Collect();
Console.WriteLine("Some More Statement Executed Inside Main Method");
GC.Collect();
Console.WriteLine("Main Method Execution End");
Console.ReadKey();
}
}
}
Output:

55
using System;
namespace DestructorExample
{
class DestructorDemo
{
public DestructorDemo()
{
Console.WriteLine("DestructorDemo Object Created");
}
~DestructorDemo()
{
Console.WriteLine("DestructorDemo Object Destroyed");
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Main Method Execution Started");
DestructorDemo obj1 = new DestructorDemo();
//Making obj1 ready for Garbage Collection
obj1 = null;
GC.Collect();
Console.WriteLine("Some Statement Executed Inside Main Method");
obj1 = null;
GC.Collect();
Console.WriteLine("Some More Statement Executed Inside Main Method");
GC.Collect();
Console.WriteLine("Main Method Execution End");
Console.ReadKey();
}
}
}
Points to Remember while working with Destructors in C#:

Point1: Destructors (or Finalizers) cannot be defined in structs. In C#, they are only used with only
classes. For a better understanding, please have a look at the below image.

56
Point2: In a class, we can only define one Destructor (or Finalizer). That means Destructors cannot be
overloaded in a class. For a better understanding, please have a look at the below code.

Point3: Destructors cannot be called Explicitly. They are invoked automatically by the garbage collector.
At most what we can do is, we can request the Garbage collector to execute the Destructor by calling
the GC.Collect() method. For a better understanding, please have a look at the below code.

57
Point4: A Destructor does not take any modifiers or does not have any parameters. They are
parameterless. For a better understanding, please have a look at the below code.

How Destructors are Implemented in C#?

Let us understand how Destructors are Implemented in C# with Examples. To understand how the
destructor is implemented in C#, please have a look at the below example.

using System;
namespace DestructorExample
{
class Sample
{
//Destructor
~Sample()
{
//Clean-up Statements
}
}
class Program
{
static void Main()
{
}
}
}
Now, if you check the IL Code of the above destructor using the ILDASM tool, then you will see the
following IL Code is generated for the above constructor.

58
As you can see, the Destructor implicitly calls the Finalize method on the base class of the object.
Therefore, a call to a destructor is implicitly translated as follows:

As you can see in the above code, the destructor is converted to Finalize method. So, whatever code you
have written inside the destructor, those codes will be goes inside the try block of the Finalize method and
that block code executes and clean-up the resources. Once the try block completes its execution, then the
finally block is going to be executed. Finally is one block which is guaranteed to be executed. From the
finally block, we are again invoking the parent class Finally method, and the parent class finalize method
again going to do the same thing.

Advertisements
AD
This design means that the Finalize method is called recursively for all instances in the inheritance chain,
from the most-derived to the least-derived. Let us understand this with an example.

In the below example, we created three classes that make a chain of multi-level inheritance. The class
First is the base class, the class Second is derived from First, and the class Third is derived from the class
Second. And most importantly all these three classes have destructors. Inside the Main method, an
instance of the most-derived class i.e. Third is created.

using System;
namespace DestructorExample
{
public class First
{

59
~First()
{
Console.WriteLine("Destructor of First Called");// Third executed
}
}
public class Second : First
{
~Second()
{
Console.WriteLine("Destructor of Second Called");// Second executed
}
}
public class Third : Second
{
~Third()
{
Console.WriteLine("Destructor of Third Called");// First executed
}
}
class Program
{
static void Main(string[] args)
{
Third obj = new Third();
obj = null;
GC.Collect();
Console.ReadKey();
}
}
}
Output:

Note1: Empty Destructors should not be used in our application.

 When a class contains a destructor, then an entry for that destructor is created in the Finalize queue.
 This is the queue that is processed by the garbage collector. When the Garbage Collector processes
the Finalize queue, it will call each destructor.
 So, Unnecessary destructors, including

1. empty destructors,
2. destructors that only call the base class destructor,
3. destructors that only call conditionally emitted methods, cause a needless loss of performance.

Note2:

 As a developer, we have no control over when the destructor is called and executed.
 It is the garbage collector in .NET Framework who decides when to call destructors.
 The garbage collector periodically checks for objects that are no longer being used by the application.
If it considers an object eligible for destruction, then it calls the destructor (if any) and reclaims the
memory used to store the object.
 It is also possible to force garbage collection by calling the GC.Collect method, but most of the time,
this call should be avoided because it may create performance issues.
 How does it impact the performance that we will discuss in our next article?

When to use Destructor in C#?

You might have one question on your mind if the memory management is automatically managed by the
garbage collector, then when do we need to use Destructor? In general, as C#.NET developers, we need

60
not be much more worried about memory management. This is because the .NET garbage collector
implicitly manages the allocation and deallocation of the memory for our objects.

However, when our application works with unmanaged resources, such as windows, files, and network
connections,

we should use a destructor to free the memory for those unmanaged resources.

When the object is eligible for destruction, the garbage collector runs the Finalize method of the object. For
a better understanding, please have a look at the following example.

using System;
namespace FileHandlinDemo
{
public class UmmanagedResource
{
public UmmanagedResource()
{
//Creating Unmanaged Resources
Console.WriteLine("Unmanaged Resource Created");
}
~UmmanagedResource()
{
//Clean up Unmanaged Resources
Console.WriteLine("Unmanaged Resource Destroyed");
}
}
class Program
{
static void Main()
{
UmmanagedResource resource = new UmmanagedResource();
Console.WriteLine("Using Unmanaged Resource");
resource = null;
GC.Collect();
Console.ReadKey();
}
}
}
Output:

Explicit Release of Resources using Dispose Pattern in C#:

If our application is using an expensive external resource, then it is recommended to provide an explicit
way to release the resources before the garbage collector frees the object. To release the resource, it is
recommended to implement a Dispose method of the IDisposable interface that performs the necessary
clean-up for the object. So, basically, we need our class to inherit from the IDisposable interface and
provide the implementation for the Dispose methods as follows. So, here, please select Implement
Interface with Dispose Pattern option as shown in the below image.

61
Once you Implement the interface with Dispose pattern, you will see the following code, The following code
is self-explained, so please go through the comment lines.

using System;
public class UmmanagedResource : IDisposable
{
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
// TODO: dispose managed state (managed objects).
}
// TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
// TODO: set large fields to null.
disposedValue = true;
}
}
// TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
// ~UmmanagedResource() {
// // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
// Dispose(false);
// }
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
// TODO: uncomment the following line if the finalizer is overridden above.
// GC.SuppressFinalize(this);
}
#endregion
}

Understanding Dispose Pattern in C#:

1. disposedValue: The disposedValue variable to identify the redundant call. Suppose, we have
requested to destroy the resources and if again we are requesting to destroy the object, then it will

62
check this field and identify whether it is a redundant call or not, and based on this it will do the clean-
up activities.
2. Dispose(bool disposing): We need to write the actual logic to destroy the managed and unmanaged
resources inside this method. This disposing variable value which this method takes as an input
parameter will identify whether we need to destroy the managed resources or not. Further, it checks
the disposedValue variable value to check whether it needs to perform the cleanup activity or not. If
the request comes for the first time, the value for the disposedValue variable will be false and in that
case, it will perform the clean-up activity and at the end, it sets the value true. So, when a redundant
request comes, it will not perform the clean-up activity.
3. ~UmmanagedResource(): By default, you will see that destructor or finalizer code is commented.
But if you want to destroy the resources through destructor, then you need to uncomment this
destructor or finalizer. But, as part of this destructor, you need to write cleanup code for managed
resources and then you need to call the Dispose(false) method to clean up the unmanaged
resources. You, need to override a finalizer or destructor only if Dispose(bool disposing) method has
code to free unmanaged resources only.
4. Dispose(): This is the method that we need to call from our code to clean up the managed and
unmanaged resources. As part of this method, we need to call Dispose(true) method which is
actually going to clean up both managed and unmanaged resources. Again, if you override the
destructor or finalizer method, then you need to call GC.SuppressFinalize(this) method which will
tell the garbage collector to just ignore the destructor i.e. informing CLR (Garbage Collector) to not
call the destructor or finalizer. You only need to uncomment this if you have overridden the destructor
or finalizer.
The above dispose pattern can considerably improve the performance of the application. Even with this
explicit control over resources, the finalizer or destructor becomes a safeguard to clean up resources if the
call to the Dispose method fails. Let us write some print statements and see the output. The complete
example code is given below.

using System;
namespace DestructorDemo
{
public class UmmanagedResource : IDisposable
{
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
//Write Code Here to Destroy the Managed Resources
Console.WriteLine("Managed Resources Destroyed by Dispose Method");
}
//Write Code Here to Destroy the Umanaged Resources
Console.WriteLine("Unmanaged Resources Destroyed by Dispose Method");
disposedValue = true;
}
else
{
Console.WriteLine("Resources are Already Destroyed by Dispose Method");
}
}
~UmmanagedResource()
{
//Write Code here to Destroy the Object
Console.WriteLine("Request Comes to Destructor to Destroy the Resources");
Dispose(false);
}
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
//Write Code here to Destroy the Object
Console.WriteLine("Request Comes to Dispose Method to Destroy the Resources");

63
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
class Program
{
static void Main()
{
UmmanagedResource resource = null;
try
{
resource = new UmmanagedResource();
Console.WriteLine("Using Resources");
}
finally
{
if (resource != null)
{
Console.WriteLine("Calling Dispose Method to Destroy Resources");
resource.Dispose();
}
}
//Trying to Call the Dispose Method again
Console.WriteLine();
Console.WriteLine("Trying to Call the Dispose Method Again To Destroy Resources");
resource.Dispose();
Console.ReadKey();
}
}
}
Output:

In the next article, I am going to discuss How Garbage Collection works in .NET Framework with
Examples. Here, in this article, I try to explain the Destructor in C# with Examples. I hope this article will
help you with your needs. I would like to have your feedback. Please post your feedback, question, or
comments about this Destructor in C# with Examples article.

64
65

You might also like