C sharp - Default Constructor in C#
What is a Default Constructor?
A default constructor is a constructor that takes no parameters. It is used to create an object and initialize it with default values.
Key Features
-
Has no parameters.
-
Can be explicitly defined by the programmer, or
-
Is automatically provided by the C# compiler if no other constructor is defined in the class.
-
Initializes fields to their default values (e.g.,
0
for int,null
for strings,false
for bool, etc.).
Syntax
class ClassName
{
public ClassName()
{
// Initialization code
}
}
Important Notes
-
If you define any constructor (e.g., parameterized), the compiler does not generate a default constructor automatically—you must define it explicitly.
-
Default constructors are useful when you want to create an object without passing any arguments.
Example:
using System;
class Person
{
public string name;
public int age;
// Default constructor
public Person()
{
name = "Unknown";
age = 0;
}
public void DisplayInfo(){
Console.WriteLine("Name: " + name);
Console.WriteLine("Age: " + age);
}
}class Program
{
static void Main()
{
// Creating object using default constructor
Person p1 = new Person();
p1.DisplayInfo();
}
}