Can we store different types in an array in C#

As we know array is a collection of similar objects.

If we create array of integer, we can pass or assign only the integer values. If we try to pass or assign any other data type value we will get a compile time error.

So, how can we store values of different data types in a single array?

We can create array of object.

As we know all types i.e. value types and complex types directly or indirectly inherits from System.Object namespace. So, we can pass any type of data to an object type.

DEMO

  1. using System;  
  2.   
  3. namespace ObjectArrays   
  4. {  
  5.     class Student   
  6.     {  
  7.         public int Id{get;set;}  
  8.         public string Name{get;set;}  
  9.         public override string ToString()  
  10.         {  
  11.             return this.Name;  
  12.         }  
  13.     }  
  14.     class Program   
  15.     {  
  16.         static void Main(string[] args)   
  17.         {  
  18.             //create an array of type object  
  19.             object[] ObjectType = new object[3];  
  20.             //in the first position, we are assigning an integer value  
  21.             ObjectType[0] = 1;  
  22.             //in the second position, we are assigning a string value.  
  23.             ObjectType[1] = "Hello";  
  24.   
  25.             Student s = new Student();  
  26.             s.Id = 1;  
  27.             s.Name = "Sam";  
  28.   
  29.             //in the third position we are assigning a complex value  
  30.             ObjectType[2] = s;  
  31.   
  32.             foreach(object objects in ObjectType)  
  33.             {  
  34.                 Console.WriteLine(objects);  
  35.             }  
  36.         }  
  37.     }  
  38. }  
Run the application.



I hope you like it and find this helpful.

Thank you for reading.