Parameterized constructor in C#

Realize: What is parameterized constructor in c#, how it is proclaimed, characterized and what parameterized constructor does?

As we have talked about that default constructors are utilized to instate information individuals from the class with the default values, and the default constructors don’t require any contentions that is the reason they called zero or no contentions constructor.

Be that as it may, on the off chance that we need to instate the information individuals from the class while making the article by sitting back for example at the point when we need to introduce the information individuals bypassing a few contentions, we use a parameterized constructor.

A parameterized constructor is the extraordinary sort of strategy which has the same name as the class and it instates the information individuals by given parameters.

Think about 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  = 121       ;
			name    = "Kishan"   ;
			age     = 21;
		}

		//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("Durgesh", 162, 25);
			//printing the values, defined by the parameterized constructor
			S2.printInfo();
		}
	}
}

Output

Student Record:
        Name     : Kishan
        RollNo   : 121
        Age      : 21
Student Record:
        Name     : Durgesh
        RollNo   : 162
        Age      : 25

Here, individuals from object S1 will be introduced through default constructor, the default values are:

Name     : Kishan
RollNo   : 121
Age      : 21

what’s more, individuals from object S2 will be instated through the parameterized constructor, the default values are:

Name     : Durgesh
RollNo   : 162
Age      : 25

Leave a Comment

error: Alert: Content is protected!!