Saturday 7 September 2019

can we store different type of data in single array in c sharp?



Answer is yes.
If you declare array with normal data types you  can’t .
Example:
int[] arr = new int[2];
arr[0] = 10;
arr[1] = "karthikeyan";
this will denote error at the compile time.
Note the string “karthikeyan” was red underlined.
But we create an array of object you can.
Example:
object[] a = new object[3];

a[0] = 12;
a[1] = "Muthu";
even you can store complex  data types in object type:
class student
    {
        public int id { get; set; }
        public string name { get; set; }
        public override string ToString()
        {
            return this.name;
        }

    }

Now we create object for student and then initialize values.
student s = new student();
            s.id -= 101;
            s.name = "Muthu karthikeyan";
now assign object s to a[2].

            a[2] = s;
to display:
foreach (object o in a)
            {
                Console.WriteLine(o);
            }
Output:
12
Muthu
Muthu karthikeyan.
And also if we create array with arraylist you can easily add different type of data in single array
Example:
ArrayList arr1 = new ArrayList();
            arr1.Add(10);
            arr1.Add("vishnu");
-Thank you
Muthu karthikeyan,Madurai.