C sharp - Parameterized Constructor
What is a Parameterized Constructor?
A parameterized constructor is a constructor that takes arguments (parameters). It allows you to initialize object properties with specific values at the time of object creation.
Why Use It?
-
To set initial values for object fields.
-
To avoid using separate setter methods after creating the object.
Syntax
class ClassName
{
public ClassName(type parameter1, type parameter2)
{
// Use parameters to initialize fields
}
}
Simple Example
using System;
class Student
{
public string name;
public int age;
// Parameterized constructor
public Student(string studentName, int studentAge)
{
name = studentName;
age = studentAge;
}
public void DisplayInfo()
{
Console.WriteLine("Name: " + name);
Console.WriteLine("Age: " + age);
}
}
class Program
{
static void Main()
{
// Create object with specific values
Student s1 = new Student("Alice", 20);
s1.DisplayInfo();
}
}