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. By IncludeHelp Last updated : April 11, 2023

Arrays can have integers, floats, doubles, etc. as its value. Whereas, an array of objects can have objects as its value.

What is an array of objects in C#?

Array of objects in C# is just an array of object data as its value. By using array of objects, you can access the members (field and methods) of the class with each object.

Array of objects declaration

The following syntax is used to declare an array of objects,

class_name array_name[] = new class_name[SIZE];

C# example of array of objects

using System;

namespace ExampleArrayOfObjects {
  // Class definition
  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];

      //Initialising objects by defaults/inbuilt 
      //constructors
      S[0] = new Student();
      S[1] = new Student();

      //Setting the values and printing first object
      S[0].SetInfo("Herry", 101, 25);
      S[0].printInfo();

      //Setting the values 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

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





Comments and Discussions!

Load comments ↻






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