C# - Create Array with Multiple Data Types

In C#, arrays are designed to store elements of the same data type. However, if you need to store elements of different data types in a collection, you can use the built-in 'object' type or create a custom class to hold multiple data types. Let's explore both approaches:

1. Using 'object' type (Boxing):
The 'object' type is a base type for all data types in C#. It can store any value, including value types (e.g., int, float) and reference types (e.g., strings, custom classes). However, using 'object' comes with the cost of boxing and unboxing, which may lead to a performance overhead.


object[] mixedArray = new object[5];

mixedArray[0] = 10;             // int
mixedArray[1] = "Hello";        // string
mixedArray[2] = 3.14f;          // float
mixedArray[3] = true;           // bool
mixedArray[4] = new MyClass();  // Custom class instance

To access the elements, you need to cast them back to their original types:


int intValue = (int)mixedArray[0];
string stringValue = (string)mixedArray[1];
float floatValue = (float)mixedArray[2];
bool boolValue = (bool)mixedArray[3];
MyClass myClassValue = (MyClass)mixedArray[4];

2. Using a custom class::
Create a custom class that holds properties for each data type you want to store. This way, you can define a single data type for your array and then create instances of the custom class to store different data types.


public class DataContainer
{
    public int IntValue { get; set; }
    public string StringValue { get; set; }
    public float FloatValue { get; set; }
    public bool BoolValue { get; set; }
}

DataContainer[] mixedArray = new DataContainer[3];

mixedArray[0] = new DataContainer { IntValue = 10 };
mixedArray[1] = new DataContainer { StringValue = "Hello" };
mixedArray[2] = new DataContainer { FloatValue = 3.14f };

Now you can access the elements directly without casting:


int intValue = mixedArray[0].IntValue;
string stringValue = mixedArray[1].StringValue;
float floatValue = mixedArray[2].FloatValue;

Using a custom class provides better type safety and avoids the performance overhead associated with boxing and unboxing.

Both approaches have their pros and cons, and the choice depends on the specific use case and requirements of your program. If possible, using a custom class is generally a better practice as it provides type safety and better code readability.