You will learn followings:
- Private Constructors in C#
- Static Constructor in C#
- Classes and Constructors in C#
Private Constructors in C#
In this article, we’ll explain about Private Constructors in C# with Examples. This article will be useful to both beginners and professional C# developers. We hope at the end of this article, all your doubts regarding Private Constructors in C# will be cleared.
What you'll learn below:
What is default Constructor?
Before moving towards Private Constructors, let’s check default Constructor first. Every class is having a default constructor or explicitly we can create constructor. By default, constructor is public, but we can make it private as per our needs. How the default constructor appears. Let’s see below
Important points of Private Constructors
- Private constructor is a special constructor which is used in a class to assign the value to private readonly variable.
- The main purpose of creating private constructor is to restrict the class from being instantiated. When you’ll try to create object, you'll see the error as “Class is inaccessible due to its protection level”.
- If a class has one or more private constructor and no public constructor, then other classes are not allowed to create instance of this class; this means you can neither create the object of the class nor it can be inherited by other classes.
Use of Private Constructor
- It is used to stop a class to be inherited
- It is used to stop instantiation of class. (Object cannot be created)
- It is used in singleton design patterns so that only one instance of a class can be created.
- Private Constructor is used to assign the value to Private readonly variable like.
Private Constructor VS Sealed class
We can convert above class in to Sealed class (shown below) by decorating the class with Sealed keyword. By using this we can increase the protection level of our class. This sealed class can be instantiated but not available for inheritance. But class with Private constructor can neither be inherited nor instantiated. Sealed class will appear as:
Ctor is a snippet and used to create default constructor. Just type Ctor in your C# class and double tab, it will write default constructor for you.
Can we create object of class having private constructor?
No, class with private constructor cannot be instantiated. Its object cannot be created. You will get compile time error that "Bank.Bank() is inaccessible due to its protection level".
When can we make private constructor in C#?
Private Constructor is a special instance constructor available in C#. Normally, we create a private constructor of class in case of singleton pattern and another example is when we have all data members as static so that we can access those directly by the name of class only.
Can we create private constructor in abstract class?
Yes, it is feasible. We can create private constructor in abstract class.
How to get instance of class having Private Constructor?
Finally, we'll explain below how to create the object of class having private constructor. For this we need to use "Activator" class.
In below image, first example shows how to create object of class having private constructor but using "Activator class". Second way is the traditional way of creating object, but it will not allow you to create object if class will have private constructor.
You can find complete source code below. For additional information you can also view our video HERE:
namespace PrivateConstructor
{
class Program
{
static void Main(string[] args)
{
//Way-1: creating object using Activator class
Type type = typeof(Bank);
Bank obj = (Bank)Activator.CreateInstance(type, true);
obj.show();
//Way-2: Creating object
//Bank obj = new Bank();
//obj.show();
Console.ReadLine();
}
}
public class Bank {
private readonly int bankid;
private Bank()
{
bankid = 101;
Console.WriteLine("1.Private constructor called... ");
}
public void show() {
Console.WriteLine("2. Show method is called...");
}
}
}
For more detail checkout below Video:
In this article I tried to explain Private Constructors in C# with Examples. I hope you enjoyed reading this article. For more information you can check out Microsoft learn.
Static Constructor in C#
In this article, we’ll explain about Static Constructor in C# with Examples. This article will be useful to both beginners and professional C# developers. We hope at the end of this article, all your doubts regarding Static Constructors in C# will be cleared.
What you’ll learn below:
What is default Constructor?
Before moving towards Static Constructors, let’s check default Constructor first. Every class is having a default constructor or explicitly we can create constructor. This default constructor is public (by default), We can also create a "static constructor" as per our needs. How the Static constructor appears, let's see below:
Static Constructor in C#: Syntax
What is Static Constructor in C#?
A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.
Overall, C# supports multiple types (4 types) of constructors, here we'll discuss only static constructor. Static constructor is used to initialize static data members as soon as the class is referenced the first time. Instance constructor is used to create an instance of that class with the ‘new’ keyword.
Important points about Static Constructor in C#
- C# static constructor cannot have any access modifier like public/private etc.
- C# static constructor cannot have any input parameter.
- C# static constructor is invoked implicitly. It can't be called explicitly.
- The static constructor for a class executes before any instance of the class is created.
- Static constructor for a class executes before any of the static members for the class are executed.
- Static constructor for a class executes at most one time in whole lifetime of program.
- The user cannot call ’static constructor’ directly and has no control on it when it is executed.
- A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
Code sample of Static Constructor:
using System;
namespace TestApplication{
public class Program{
static void Main(string[] args){
Bank obj = new Bank ();
//Bank obj1 = new Bank ();
Console.ReadLine();
}
}
public class Bank{
static Bank()
{
Console.WriteLine("Static constructor is called");
}
public Bank ()
{
Console.WriteLine("Default constructor is called");
}
}
}
Out will be:
Static constructor is called.
Default constructor is called
Default constructor is called
Can we initialize non-static data fields within static constructor?
It is not possible to initialize non-static data fields within the static constructor, it will give compile time error. But we can initialize static data fields within a non-static constructor.
What happens if static constructor throws an exception?
If a static constructor throws an exception, the runtime will not invoke it a second time, and the static data members will remain uninitialized for the lifetime of the application. Error will be as
Can we use access modifiers & input parameter in static constructor?
No, we cannot pass input parameter and defining access modifier is also not feasible in static constructor. This in not feasible because 'static constructor' is the first piece of code that execute when that class is referred first time.
In this article I tried to explain Static Constructors in C# with Examples. I hope you enjoyed reading this article. For more information you can check out Microsoft learn.
For more info see video too:
Classes and Constructors in C#
In this post we'll learn about C# | Classes and Constructors. Below we are going to talk about:
- Adding New Elements in Solution Explorer
- Defining Classes and How to Use Them
- Constructors
- Constructor Overloading
- Partial Classes
Adding New Elements in Solution Explorer
Even though we can create new classes inside the Program.cs file, it is much better to create a new class in a separate file. To do that, we need to right-click on our project name, choose Add and then New Item (Ctrl+Shift+A). Post this we need to choose a class file and add a name:
Defining Classes and How to Use Them
In C#, to define a class, we need to use the class keyword. The class consists of members. All the class members are defined in the class body between two curly braces:
public class Student
{
private string _name;
private string _lastName;
public string GetFullName()
{
return _name + ' ' + _lastName;
}
}
We see that the body contains two private fields (variables in the class body are called fields) _name and _lastName and one public method GetFullName (if you are not familiar with the access modifiers: private, public, etc. you can read more about them in our module 1 about C# basics).
Now the student object can access the members from the student class. For now, we have only one method inside the student class and we can call it with the student.GetFullName() syntax. This will return an empty string, but we are going to fix that as soon as we introduce constructors.
It is so important not to confuse the terms class and object. The class is a type definition but an object is an instance of that type. We can have several object instances of the same class:
class Program
{
static void Main(string[] args)
{
Student student = new Student();
}
}
Student student = new Student();
Student student1 = new Student();
Student student2 = new Student();
Student student3 = new Student();
Constructors
When you create an object using the new keyword, the CLR (common language runtime) uses the class definition to call the constructor method to create the object. A constructor is a special method that has the same name as the class in which it is defined, does not return a value (not even void), and can take parameters. It runs automatically when you create an instance of the class. Each time you instantiate a class using the new keyword, you call the constructor for that class.
Check more on Constructors in above section of this article:
Private Constructors in C#Static Constructor in C#
All classes require a constructor. If you do not write it, the compiler will automatically generate it. This type of constructor is called a default constructor. The default constructor sets all data in the class to its default value (or the assigned value if not assigned). In this example, the _name and _lastName fields have leading null values. This is because it is the default value for reference types.
We can write our own default constructor as well:
public class Student
{
private string _name;
private string _lastName;
public Student()
{
_name = string.Empty;
_lastName = string.Empty;
}
public string GetFullName()
{
return _name + ' ' + _lastName;
}
}
Constructor Overloading
Our classes are not limited to just one constructor method. You can create more of these in one class:
public class Student
{
private string _name;
private string _lastName;
public Student()
{
_name = string.Empty;
_lastName = string.Empty;
}
public Student(string name, string lastName)
{
_name = name;
_lastName = lastName;
}
public string GetFullName()
{
return _name + ' ' + _lastName;
}
}
Now we have two options to instantiate our class,
First one with the default values and second one is overloaded one, which gives us the ability to set the values of our fields:
class Program
{
static void Main(string[] args)
{
Student student = new Student(); //default constructor
Student student1 = new Student("John", "Doe");//overloaded constructor
Console.WriteLine(student1.GetFullName());
}
}
There is one important thing to have in mind. If we create our own constructor for a class, the compiler won’t create a default one for us. So, if we want to have a default one and the overloaded one, we must create both of them.
Partial Classes
In a real project, this could be a very large class with many, many lines of code. This type of class can be less readable and more difficult to maintain. To avoid this, you can use partial classes. Partial classes also have the added benefit of allowing multiple developers to work on the same class at the same time. Additionally, you can also create partial methods within these classes. In nutshell a partial class is nothing more than a part of a single class. To define partial classes, we need to use the partial keyword in each file:
partial class Student
{
private string _name;
private string _lastName;
public Student()
{
_name = string.Empty;
_lastName = string.Empty;
}
}
partial class Student
{
public Student(string name, string lastName)
{
_name = name;
_lastName = lastName;
}
public string GetFullName()
{
return _name + ' ' + _lastName;
I hope you enjoyed reading this post. For more information you can check out Microsoft learn.










No comments:
Post a Comment