How to call parameterized constructor using an array of objects in C#?

Realize: How to call parameterized constructor using exhibit of items in C#.Net? In this example, we are using the parameterized constructor to introduce the individuals from the class.

We have just talked about parameterized constructor and exhibit of articles in C#.Net, in this example, we are using the two ideas cluster of items and parameterized constructor. Here information individuals from the class will be introduced through the constructors.

Think about the example:

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

namespace ConsoleApplication1
{
	class Student
	{
		//private data members
		private int     rollno  ;
		private string  name    ;
		private int     age     ;
		
		//default constructor
		public Student()
		{
			rollno = 121;
			name   = "Kishan";
			age    = 16;
		}
		
		//parameterized constructor 
		public Student(string name, int rollno, int age) 
		{
			this.rollno = rollno  ;
			this.age  = age;
			this.name = name;
		}

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

	}

	//class, containing main method
	class Program
	{
		//main method
		static void Main()
		{
			//array of objects
			Student[] S = new Student[2];
			//here, default constructor will be called
			S[0] = new Student();
			//here, parameterized constructor will be called
			S[1] = new Student("Aakash", 117, 18);
			
			//printing both objects
			S[0].printInfo();
			S[1].printInfo();
		}
	}
}

Output

Student Record:
        Name     : Kishan
        RollNo   : 121
        Age      : 16
Student Record:
        Name     : Aakash
        RollNo   : 117
        Age      : 18

Here, information individuals from S[0] item will be introduced through default constructor and information individuals from S[1] article will be instated through the parameterized constructor.

Leave a Comment

error: Alert: Content is protected!!