C# - Retrieve Different Data Types From an Object Array

To retrieve different data types from an 'object' array in C#, you can use type casting. Since an 'object' array can store values of different data types (as all data types are implicitly convertible to the object type), you need to explicitly cast the elements back to their original data types before using them.

Here's an example of how to retrieve different data types from an object array:


object[] mixedArray = new object[5];

mixedArray[0] = 10;             // int
mixedArray[1] = "Hello";        // string
mixedArray[2] = 3.14f;          // float
mixedArray[3] = true;           // bool
mixedArray[4] = "2023-07-26";   // string representing a date

// Retrieving different data types from the object array
int intValue = (int)mixedArray[0];
string stringValue1 = (string)mixedArray[1];
float floatValue = (float)mixedArray[2];
bool boolValue = (bool)mixedArray[3];
string stringValue2 = (string)mixedArray[4];

// Example of parsing a date from a string
DateTime dateValue;
if (DateTime.TryParse(stringValue2, out dateValue))
{
    Console.WriteLine("Parsed date: " + dateValue.ToString("yyyy-MM-dd"));
}
else
{
    Console.WriteLine("Invalid date format.");
}

In this example, the object array 'mixedArray' contains values of various data types, such as 'int', 'string', 'float', and 'bool'. To retrieve these values, we use explicit type casting, like '(int)mixedArray[0]', '(string)mixedArray[1]', etc., to convert the 'object' type elements back to their original data types.

Keep in mind that type casting might cause runtime exceptions if the cast is not valid. Always ensure that the elements in the object array are of the expected data types before attempting to cast them. Additionally, when using type casting with object arrays, there is a possibility of boxing and unboxing, which may have a performance impact if used excessively. In cases where you need to work with different data types frequently, using a custom class or a generic data structure may provide a more efficient and type-safe solution.