Home » .Net

Array of objects in C#

C# Array of Objects: Learn how to declare array of objects in C#? How to access methods of class using objects? Explain the concept of Array of Objects with an Example.

As we know that, we can create array of integers, floats, doubles etc. Similarly we can create array of objects.

By using this array of objects, we can access methods of class with each object (which are the elements of that array).

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     ;       

		//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   );
		}

	}

	class Program
	{
		static void Main()
		{
			//creating array of objects
			Student[] S = new Student[2];
			//initlising objects by detauls/inbuilt constructors
			S[0] = new Student();
			S[1] = new Student();
			//reading and printing first object
			S[0].SetInfo("Herry", 101, 25);
			S[0].printInfo();
			//reading and printing second object
			S[1].SetInfo("Potter", 102, 27);
			S[1].printInfo();

		}
	}
}

Output

Student Record:
        Name     : Herry
        RollNo   : 101
        Age      : 25
Student Record:
        Name     : Potter
        RollNo   : 102
        Age      : 27

Here, we created a class for student and created array of objects to read, print the details of the students.





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.