Home » .Net

Parameterized constructor in C#

Learn: What is parameterized constructor in c#, how it is declared, defined and what parameterized constructor does?

As we have discussed that default constructors are used to initialize data members of the class with the default values, and the default constructors do not require any arguments that’s why they called zero or no arguments constructor.

But, if we want to initialize the data members of the class while creating the object by passing values at run time i.e. when we want to initialize the data members by passing some arguments, we use parameterized constructor.

Parameterized constructor is the special type of method which has same name as class and it initialize the data members by given parameters.

Consider the example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{

	//class definition
	class Student
	{
		//private data members 
		private int     rollno  ;
		private string  name    ;
		private int     age     ;

		//default constructor 
		public Student()
		{
			//initializing data members with default values
			rollno  = 101       ;
			name    = "Herry"   ;
			age     = 12;
		}

		//parameterized constructor 
		public Student(string name, int rollno, int age) 
		{
			//initializing data members with passed arguments 
			this.rollno = rollno  ;
			this.age  = age;
			this.name = name;
		}		

		//method to set values 
		public void setInfo(string name, int rollno, int age) 
		{
			this.rollno = rollno  ;
			this.age  = age;
			this.name = name;
		}

		//method to display values
		public void printInfo()
		{
			Console.WriteLine("Student Record: ");
			Console.WriteLine("\tName     : " + name  );
			Console.WriteLine("\tRollNo   : " + rollno);
			Console.WriteLine("\tAge      : " + age   );
		}

	}

	//main class, in which we are writing main method
	class Program
	{
		//main method
		static void Main()
		{
			//creating object of student class
			Student S1 = new Student();
			//printing the values, initialized through 
			//default constructor 
			S1.printInfo();

			//creating another object 
			Student S2 = new Student("George", 102, 13);
			//printing the values, defined by the parameterized constructor
			S2.printInfo();
		}
	}
}

Output

Student Record:
        Name     : Herry
        RollNo   : 101
        Age      : 12
Student Record:
        Name     : George
        RollNo   : 102
        Age      : 13

Here, members of object S1 are going to be initialized through default constructor, the default values are:

Name : "Herry"
RollNo: 101
Age : 12

and, members of object S2 are going to be initialized through parameterized constructor, the default values are:

Name : "George"
RollNo: 102
Age : 13


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.