Home » .Net

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

Learn: How to call parameterized constructor using array of objects in C#.Net? In this example, we are using parameterized constructor to initialize the members of class.

We have already discussed about parameterized constructor and array of objects in C#.Net, in this example we are using the both concepts array of objects and parameterized constructor. Here data members of the class will be initialized through the constructors.

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;
		}
		
		//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("Potter", 102, 27);
			
			//printing both objects
			S[0].printInfo();
			S[1].printInfo();
		}
	}
}

Output

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

Here, data members of S[0] object will be initialized through default constructor and data members of S[1] object will be initialized through parameterized constructor.



Comments and Discussions!

Load comments ↻





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