.NET FAQs Unleashed!
 
    
    

Can multiple data types be stored in System.Array?

So whats an array all about? An array is a collection of items of the same type, that is grouped together and encompassed within an array object. The array object, or the System.Array object to be precise, is derived from the System.Object class. It is thus, stored in the form of a heap in the memory.
An array may be of single dimensional, multi-dimensional or jagged (a jagged array means an array within an array).

A group of items when assigned values within braces implicitly derive from System.Array class. See example below written in C#...

C# Example
int[] testIntArray = new int[4] { 2, 3, 4, 5 };
Object[] testObjArray = new Object[5] { 32, 22, 23, 69, 75 };

Ideally an array should contain a single data type. But still in case there is a requirement to place data of different data types in a specific array, then in such a scenario, the data elements should be declared as an object type. When this is done, then each element may point ultimately to a different data type. See code example below written in VB.NET...

VB.NET Example
Dim allTypes As Object() = New Object() {}

'In this kind of scenario, the performance may tend to slow down, as data conversions may take place.
'In case a value type is converted to reference type, then boxing and unboxing occurs
'To know more on Value Types & Reference Types, Click Here

Dim studentTable(2) As Object
studendTable(0) = "Vishal Khanna"
studentTable(1) = 28
studentTable(2) = #9/1/1978#

'To get these values of these varying datatypes, their values are converted to their original data type

Dim myAge As Integer = CInt(studentTable(1))
Dim myBirthDay as Date = CDate(studentTable(2))

Protected Internal  Array  Sort Array  Throw  Multiple Catch  Polymorphism  Inheritance  Session Viewstate  Autogenerate  ReadOnly  Sealed Class  Sealed Method  Multiple Interfaces  Overloading  Overloaded Constructors  Generics  Main  Case Sensitive  Console  Specifier  Return Type  SetCommandLineArgs  System Environment  New  Default Values of Types Compiler Error Constant Variable Const Const - ReadOnly Parameter Modifier Out Ref Interface Interface Reference, is, as System.Collection

More Interview Questions...