What is parameterized Constructor in C#?
A parameterized constructor in C# is a constructor that accepts one or more parameters when creating an object of a class. It allows you to provide specific values during the object's instantiation, which can be used to initialize the object's attributes (fields) to meaningful values.
In a parameterized constructor, you define the parameters that it expects, and you use these parameters to set the attributes of the object being created. This helps ensure that objects start with the desired initial state when they are instantiated.
Here's an example of a parameterized constructor in C#:
class Person {
public string Name { get; set; }
public int Age { get; set; }
// Parameterized constructor
public Person(string name, int age) {
Name = name;
Age = age;
}
}
class Program {
static void Main(string[] args) {
// Creating an object using the parameterized constructor
Person person = new Person("Alice", 25);
// Accessing the attributes
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
}
}
In this example, the 'Person' class has a parameterized constructor that takes two parameters: 'name' and 'age' . When you create an object using this constructor, you provide values for these parameters, which are then used to initialize the object's 'Name' and 'Age' attributes.
Parameterized constructors are useful when you want to create objects with specific initial values, making the object creation process more flexible and customizable.