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

Realize: How to make an exhibit of items in C#? How to configuration default constructors and calling the constructors with the items (made by a cluster of articles) with example?

In the last post, we have talked about a cluster of articles in C#. Here, we will realize, how to make/structure default constructors and how to get to/call them using objects (which are made by an exhibit of articles).

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;
		}
		
		//method to set student details
		public void SetInfo(string name, int rollno, int age) 
		{
			this.rollno = rollno  ;
			this.age  = age;
			this.name = name;
		}

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

	}

	//main program, it contains main method
	class Program
	{
		//main method
		static void Main()
		{
			//object creation
			Student[] S = new Student[2];
			//object initialisation with default constructors
			S[0] = new Student();
			S[1] = new Student();
			//printing the first object
			S[0].printInfo();
			//set different values in second object
			S[1].SetInfo("Aakash", 117, 18);
			//printing the second object
			S[1].printInfo();
		}
	}
}

Output

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

In this program, there are two components of a cluster of items S[0] and S[1], both are calling default constructor when articles are being made.

For the second article S[1], we are calling strategy setInfo() that will supplant the default values, which are relegated through default constructor.

Leave a Comment

error: Alert: Content is protected!!