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



I hope you like it and find this helpful.

Thank you for reading.