Can you store multiple data types in an Array in C# ?

No, we cannot store multiple datatype in an Array, we can store similar datatype only in an Array.

How to Create an Array with different data types

In C#, arrays are designed to hold elements of the same data type. However, you can achieve the desired functionality of storing different data types by utilizing the common base type for all types, such as object.

Here's an example of creating an array with different data types:

object[] myArray = new object[3]; myArray[0] = 10; // Integer myArray[1] = "Hello, World!"; // String myArray[2] = 3.14; // Double

In the above code, an array of type object[] is created with a length of 3. The object type can hold any other type since it is the base type for all types in C#. The elements of the array are assigned values of different data types: an integer, a string, and a double.

However, it's important to note that accessing elements of this array will require casting the elements back to their original types when retrieving them, as they will be treated as object types by default. For example:

int number = (int)myArray[0]; // Casting to integer string message = (string)myArray[1]; // Casting to string double pi = (double)myArray[2]; // Casting to double

By casting the elements back to their original types, you can retrieve and work with the data as intended. Keep in mind that improper casting can lead to runtime errors if the casted types do not match the actual types stored in the array.

Conclusion

Alternatively, if you have a specific requirement to work with different data types, you might consider using collection classes like List<object> or creating a custom class or structure to hold values of different types in a more structured manner.