.NET Core  

What is a Constructor?

A constructor is a special method inside a class that runs automatically when an object is created.

1.It has the same name as the class
2.It has no return type (not even void)
3.It is used to initialize variables
4.It is used to give starting values
5.It is used to inject dependencies (like DbContext in ASP.NET Core)

Real-Life Example

Imagine a car.

When you buy a car:

  • The company sets:

    • color

    • engine type

    • model year

This setup happens once when the car is built.

This is exactly what a constructor does in OOP.

Basic example in C#

Class without constructor

public class Person
{
    public string Name;
    public int Age;
}

Usage

Person p = new Person();
p.Name = "Sandhiya";
p.Age = 22;

Here we manually set Name and Age.

Class with constructor

public class Person
{
    public string Name;
    public int Age;

    // Constructor
    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }
}

Usage

Person p = new Person("Sandhiya", 22);

Constructor automatically sets Name and Age.
No need to set them manually.

Types of Constructors

1. Default Constructor (No parameters)

public class Student
{
    public Student()
    {
        Console.WriteLine("Default Constructor Called!");
    }
}

Usage

Student s = new Student(); // prints message

2.Parameterized Constructor (With parameters)

public class Student
{
    public string Name;

    public Student(string name)
    {
        Name = name;
    }
}

Usage

Student s = new Student("Priya");

3. Multiple Constructors (Constructor Overloading)

public class Book
{
    public string Title;
    public int Pages;

    public Book(string title)
    {
        Title = title;
    }

    public Book(string title, int pages)
    {
        Title = title;
        Pages = pages;
    }
}

Usage

Book b1 = new Book("C# Basics");
Book b2 = new Book("ASP.NET Core", 200);

Constructor in ASP.NET Core

This is known as Dependency Injection Constructor.

private readonly ApplicationDbContext _context;

public AccountController(ApplicationDbContext context)
{
    _context = context;
}

Explanation

  • ASP.NET Core automatically sends (injects) ApplicationDbContext into this constructor.

  • _context is now ready to use in your controller.

  • You can call:

_context.Users.ToList();

This gives you the database users.

Super simple sumary

ConceptMeaning
ConstructorRuns automatically when object created
Default constructorNo parameters
Parameterized constructorTakes values to initialize variables
Dependency Injection constructorASP.NET Core gives service objects (like DbContext) automatically