C# Parameterized Constructor

In the last chapter, we learned about Constructor and Destructor in C#, and we had also listed about constructor types, so in this chapter, we will learn about C# Parameterized Constructor.

Parameterized Constructor in C# takes one or more arguments inside constructor, basically it has same name as class name but with one or more arguments.

Let's consider a Student Class which have both Default and parameterized constructor, using later one, we can initialize values of class properties

public class Student{

  public String name;
  public int age;

  //default constructor
  public Student()   
  {
    name = "Pardeep";
    last = "Kumar";
    age = 18;
  }
   //parameterized constructor
  public Student(String fullname,int a)    
  {
    name = fullname;
    age = a;
  }
}

So to initialize object using parametized constructor in C#, you need to pass value also

//call parameterized constructor
Student stud= new Student("Vikram Motwani",28);

Let's take a look at an complete example of parametized constructor in C#

using System;
				
public class Student
{
  public String name,last;
  public int age;
 //default constructor
  public Student()   
  {
    name = "Vikram Motwani";
    age = 20;
  }
  //Parameterized constructor
  public Student(String fullName,int a)    
  {
    name = fullName;
    age = a;
  }

 
  public void display()
  {
    Console.WriteLine("Name="+name);
    Console.WriteLine("Age="+ age);
  }
}

public class Program
{
  public static void Main()
  {
    Student obj = new Student();
    obj.display();
	  Console.WriteLine();

    Student obj1 = new Student("Vikram Bajaj",21);
	Console.WriteLine("Using paramterized constructor");
    obj1.display();

  }
}

Output:

Name=Vikram Motwani
Age=20

Using paramterized constructor
Name=Vikram Bajaj
Age=21

As you can see in the above example, name "Vikram Motwani" is printed using Default constructor when no values are passed while creating object, but when paramterized constructor is used we are passing name = "Vikram Bajaj" and Age=21, which is then printed using it's object.Display() method.

In the next chapter, we will learn about Static Constructor in C#


Share Tweet