Understanding Constructors in C#: Initializing Objects and Setting Initial State
Learn about constructors in C#, special methods that initialize objects when they are created. This tutorial explains default constructors and parameterized constructors, demonstrating how to set initial values for object fields and control object initialization during creation.
Understanding Constructors in C#
In C#, a constructor is a special method that's automatically called when you create a new object (instance) of a class or struct. Its main purpose is to initialize the object's fields (data members) to their initial state.
Types of Constructors
C# supports two main types of constructors:
- Default Constructor: A constructor with no parameters. If you don't explicitly define any constructors in a class, C# provides a default constructor automatically.
- Parameterized Constructor: A constructor that takes parameters. This allows you to pass different values when creating new objects.
Default Constructor
A default constructor is invoked when you create an object without providing any arguments. Here are examples showing how the default constructor is called when creating new `Employee` objects (the `Main` method is either in the same class or a separate class):
public class Employee {
public Employee() {
Console.WriteLine("Default constructor called.");
}
}
// ... (Main method to create Employee objects) ...
Parameterized Constructor
Parameterized constructors take arguments, allowing you to initialize an object with specific values during its creation. Each object created using a parameterized constructor can have a different state based on the arguments.
public class Employee {
public int Id;
public string Name;
public float Salary;
public Employee(int id, string name, float salary) {
Id = id;
Name = name;
Salary = salary;
}
}
// ... (Main method to demonstrate) ...