Interviews6 answers
How to create an array with multiple data types in C#?
6 Answers
Using ArrayList
Sujeet SinghPosted Jul 22, 2018, 9:23 AM EDT
Object[] a=new object [20]
Mukesh KumarPosted Aug 29, 2017, 5:00 PM EDT
When you declare the array as an Object, you can have different data types. Since System.Object is the base class of all other types, an item in an array of Objects can have a reference to any other type of object.
1
2
3
4
5
object[] TestArray = new object[4];
TestArray[0]=7;
TestArray[1]=System.DateTime.Now;
TestArray[2]="Tina";
TestArray[3]=true;
In order to retrieve different data types from an Object array, you can convert an element to the appropriate data type.
int id = int.Parse(TestArray(0));
DateTime joiningDate = DateTime.Parse(TestArray(1));
As an alternative to Object array, you can use System.Collections.ArrayList.
Adi SrivastavaPosted Aug 1, 2017, 12:01 AM EDT
You can Use ArrayList in which use can multiple data type.
ArrayList aa = new ArrayList();
aa.Add(false);
aa.Add(1);
aa.Add("Name");
when you want to retrieve the data from arraylist , you have to type cast the data.
sushil kumarPosted Jul 20, 2017, 9:46 AM EDT
You have to use the object array when you want to create an array of multiple data types in C#.
Alok TripathiPosted Mar 29, 2017, 12:03 AM EDT
By declaring the array as an Object you can have multiple data types.
object[] requiredArray = new object[5];
As System.Object is the base class of all other types, an item in an array of Objects can have a reference to any other type of object.
Could be used as,
requiredArray [0]=2016;
requiredArray [1]=System.DateTime.Now;
requiredArray [2]="CodewithKasam";
requiredArray [3]=true;
requiredArray [4]= 4.6;
Hope it answers the question.
Kasam ShaikhPosted Sep 20, 2016, 3:54 AM EDT



