Can a single array have different data types in C#?

Answer: In C# programming, Array is homogeneous in nature, So, It cannot hold multiple data types e.g. int, String and bool etc. However, by declaring an array as object [] can be used to store different data type.

As Object type is the base class of all the data types, if an array is declared as object type then all type of data can be stored in an array.

Strongly Typed or homogenous array will be declared like below syntax. Strongly type array means it can store same type of data only as it has been declared.

int[] array = new int[5];

Object type array – C# code example

Hold multiple data types.

class Program
{
    static void Main(string[] args)
    {
        //Create an array of object type that
        //can store multiple data types   
        object[] objAarray = new object[3];

        //Store int type
        objAarray[0] = 5;
        //Store bool type
        objAarray[1] = true;
        //Store String type
        objAarray[2] = "interviewsansar";

        //Read data from array of object type

        foreach (Object item in objAarray)
        {
            Console.WriteLine(item);
        }
    }   
}

Related Posts