Home » .Net

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

Learn: How to create array of objects in C#? How to design default constructors and calling the constructors with the objects (created by array of objects) with example?

In the last post, we have discussed about array of objects in C#. Here, we are going to learn, how to create/design default constructors and how to access/call them using objects (which are created by array of objects).

Consider 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 = 100;
			name   = "Harmaini";
			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("Potter", 102, 27);
			//printing the second object
			S[1].printInfo();
		}
	}
}

Output

Student Record:
        Name     : Harmaini
        RollNo   : 100
        Age      : 16
Student Record:
        Name     : Potter
        RollNo   : 102
        Age      : 27

In this program, there are two elements of array of objects S[0] and S[1], both are calling default constructor when objects are being created.

For second object S[1], we are calling method setInfo() that will replace the default values, which are assigned through default constructor.



Comments and Discussions!

Load comments ↻





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