20
DecUnderstanding Constructors in C#: A Complete Guide
C# Constructor
Constructors in C# is an important concept in C# programming language. If you have doubts about how to initialize and set up an object in our program. Then, you need to understand Constructor in C#. Whenever you create an object, a constructor is the first thing that runs to make sure the object is ready to go.
In this C# Tutorial, we will get the chance to learn about What is the Constructor in C#?, the Types of Constructors in C#, default constructor in c#, parameterized constructor in c#, copy constructor in c#, private constructor in c#, and static constructor in c#
What is a Constructor in C#?
Constructor in C# is a special method with the same name as the class, used to initialize objects when they are created. It is automatically called when an object is instantiated, allowing initialization of class members and execution of specific logic before the object is used.
Syntax
class Scholar
{
.......
// Constructor
public Scholar() {}
.......
}
// An object is created of Scholar class,
// So above constructor is called
Important Points to Remember About Constructors in C#
- A class's constructor must share the same name as the class it belongs to.
- A constructor cannot be synchronized, final, or abstract.
- Only one static constructor can be created per class.
- There is no return type, not even void, for a constructor.
- A parameterized constructor can't be a static constructor.
- There can be any number of constructors in a class.
- Access modifiers can be used in the constructor declaration to limit access to a constructor, or what other classes may call it.
Read More: |
C# Developer Roadmap |
Introduction to C# |
AsynA Beginner's Guide to Async and Await in C#: Make Your Code Run Smoothly |
Types of Constructors in C#
There are 5 types of constructors in C#:
1. Default Constructor in C#
Default constructors are constructors that take no parameters. Every instance of the class must be initialized with identical values when using a default constructor. Inside a class, the default constructor sets all of the numeric values to zero and all of the string and object fields to null.
Example
using System;
class Person
{
// Properties
public string Name { get; set; }
public int Age { get; set; }
// Default Constructor
public Person()
{
Name = "Aman Mishra";
Age = 30;
}
}
class Program
{
static void Main()
{
// Creating an instance of the Person class using the default constructor
Person person = new Person();
// Printing the values
Console.WriteLine("Name: " + person.Name);
Console.WriteLine("Age: " + person.Age);
}
}
Explanation
In this example, the Person class has a default constructor that initializes the Name property to "John Doe" and the Age property to 30. In the main method of the program class, an instance of the person class is created using the default constructor, and then the name and age values are printed on the console.
Output
Name: Aman Mishra
Age: 30
2. Parameterized Constructor in C#
A constructor is considered parameterized if it accepts at least one parameter. Each instance of the class may have a different initialization value.
Example
// C# Program to illustrate calling of parameterized constructor.
using System;
namespace ParameterizedConstructorExample {
class Scholar {
// data members of the class.
String name;
int id;
// parameterized constructor would
// initialized data members with
// the values of passed arguments
// while object of that class created.
Scholar(String name, int id)
{
this.name = name;
this.id = id;
}
// Main Method
public static void Main()
{
// This will invoke parameterized
// constructor.
Scholar scholar1 = new Scholar("DNT", 1);
Console.WriteLine("ScholarName = " + scholar1.name +
" and ScholarId = " + scholar1.id);
}
}
}
Explanation
This C# code defines a Scholar class with a parameterized constructor. It creates an object scholar1, initializes its name and id, and then prints the values.
Output
ScholarName = DNT and ScholarId = 1
3. Copy Constructor in C#
This constructor generates an object by copying variables from another object. Its primary function is to set a new instance's starting values to those of an existing instance.
Example
// C# Program to illustrate calling a Copy constructor
// C# Program to illustrate calling a Copy constructor
using System;
namespace copyConstructorExample
{
class Scholars
{
private string month;
private int year;
// Declaring Copy constructor
public Scholars(Scholars s)
{
month = s.month;
year = s.year;
}
// Instance constructor
public Scholars(string month, int year)
{
this.month = month;
this.year = year;
}
// Get details of Scholars
public string Details
{
get
{
return "Month: " + month.ToString() + "\nYear: " + year.ToString();
}
}
// Main Method
public static void Main()
{
// Create a new Scholars object.
Scholars g1 = new Scholars("August", 2023);
// here is g1 details is copied to g2.
Scholars g2 = new Scholars(g1);
Console.WriteLine(g2.Details);
}
}
}
Explanation
This C# code in the C# Editor demonstrates a copy constructor in the Scholars class. It creates objects g1 and g2, where g2 is initialized using the copy constructor, displaying g1's details.
Output
Month: August
Year: 2023
4. Private Constructor in C#
A constructor is referred to as a private constructor if it was created with the private specifier. This class cannot be derived from by any other classes, nor can an instance of this class be created.
Example
// A Private Constructor
using System;
namespace privateConstructorExample
{
public class Scholars
{
// Declare a private constructor
private Scholars()
{
}
// Declare a static variable field
public static int count_scholars;
// Declare a static method
public static int scholars_Count()
{
return ++count_scholars;
}
public static void Main()
{
// If you uncomment the following
// statement, it will generate
// an error because the constructor
// is inaccessible:
// Scholars s = new Scholars(); // Error
Scholars.count_scholars = 199;
// Accessing without any instance of the class
Scholars.scholars_Count();
Console.WriteLine(Scholars.count_scholars);
// Accessing without any instance of the class
Scholars.scholars_Count();
Console.WriteLine(Scholars.count_scholars);
}
}
}
Explanation
This C# code demonstrates a private constructor in the Scholars class, preventing object creation from outside the class. It uses a static method to access and modify a static variable.
Output
200
201
5. Static Constructor in C#
When the first reference to a static member of the class was created, the static constructor—which only has to be called once in the whole class—was called. Static constructors are designed to be used just once to initialize static class fields or data.
Example
// A Static Constructor
using System;
namespace staticConstructorExample {
class scholars {
// It is invoked before the first
// instance constructor is run.
static scholars()
{
// The following statement produces
// the first line of output,
// and the line occurs only once.
Console.WriteLine("Static Constructor");
}
// Instance constructor.
public scholars(int i)
{
Console.WriteLine("Instance Constructor " + i);
}
// Instance method.
public string scholars_detail(string name, int id)
{
return "Name:" + name + " id:" + id;
}
// Main Method
public static void Main()
{
// Here Both Static and instance
// constructors are invoked for
// first instance
scholars obj = new scholars(1);
Console.WriteLine(obj.scholars_detail("DNT", 1));
// Here only instance constructor
// will be invoked
scholars obj1 = new scholars(2);
Console.WriteLine(obj1.scholars_detail("DotNetTricks", 2));
}
}
}
Explanation
This C# code demonstrates static and instance constructors. The static constructor runs once before any instance is created. Instance constructors are called for each object instance created.
Output
Static Constructor
Instance Constructor 1
Name:DNT id:1
Instance Constructor 2
Name:DotNetTicks id:2
Read More: |
Top 50 C# Interview Questions and Answers To Get Hired |
OOPs Interview Questions and Answers in C# |
Conclusion
In conclusion, we have covered Constructor in C#. You should have strong knowledge of Constructor in C#. The more you explore and build with C#, the more you'll appreciate the power of constructors in keeping your code clean, efficient, and easy to maintain. For mastering C#, ScholarHat provides you with a Full-Stack .NET Developer Certification Training Course and .Net Microservices with Docker & Kubernetes Certification Training for your brighter career.
FAQs
Take our Csharp skill challenge to evaluate yourself!
In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.