How to declare an array of Custom Type


In this article we will see that how we can create arrays of custom types. We can achieve it by using custom types.

We all know that array is a reference type i.e. memory for an array is allocated in a heap.

Sometimes we need to declare arrays of custom types rather than arrays of predefined types ( int or string etc).

Following are the steps to declare an array of custom type:

Step1: Start a new console application project.

Step2: Create a class Employee as shown below:

class Employee
    {
        public string empName { set; get; }
        public string empAddress { set; get; }
    }

Step3: Declare the array of two employees in the same way as we are declaring it for predefined datatype.

Employee[] newEmployee = new Employee[2];

array1.gif

Here new employee is the array of Employee. Here we have given the size of this array as 2 so it will create two reference types. Each will point to Employee class.

Code:

using System;
using System.Collections.Generic;
using System.Linq;
using
System.Text;

namespace UsingRefTypeInArray
{
    class Program
    {
        static void Main(string[] args)
        {
            Employee[] newEmployee = new Employee[2];
            newEmployee[0] = new Employee { empName = "Ravish", empAddress = "Haryana" };
            newEmployee[1] = new Employee { empName = "Nihar", empAddress = "Udisa" };
            Console.WriteLine("Employee Details");
            foreach (var v in newEmployee)
            {
                Console.WriteLine("NAme:" + v.empName + " Address: "+  v.empAddress +"\nNext\n");
            }
            Console.Read();
        }
    }

    class Employee
    {
        public string empName { set; get; }
        public string empAddress { set; get; }
    }
}


When we execute it than we will get the output in the below format:

array2.gif

In this way we can create an array of custom types and retrieve the value from it.

Thank You!

Ravish



 


Similar Articles