Let's say I have an array I need to store string values as well as double values. I know I can store the doubles as strings, and just deal with the conversions, but is it possible to use an array with two data types?
sure use:
object[], ArrayList, or List<Object>;
You'll have to cast, and probably pay a boxing penalty for the doubles, but they will allow you to store two different types.
object[]
and ArrayList
are two decent options; it depends on whether you need a traditional fixed-length array or a vector (variable-length array). Further, I would "wrap" one of these in a custom class that did some type-checking, if strings and doubles are the ONLY things you can deal with, and you need to be able to get them back out as strings and doubles.
You may use object[]
and do some type checking. You will get some boxing/unboxing when accessing the doubles, but that will be faster than double.Parse()
anyway.
An alternative is to create a class with both types and a marker:
class StringOrDouble
{
private double d;
private string s;
private bool isString;
StringOrDouble(double d)
{
this.d = d;
isString = false;
}
StringOrDouble(string s)
{
this.s = s;
isString = true;
}
double D
{
get
{
if (isString)
throw new InvalidOperationException("this is a string");
return d;
}
}
string S
{
get
{
if (!isString)
throw new InvalidOperationException("this is a double");
return s;
}
}
bool IsString { get { return isString; } }
}
and then create an array of StringOrDouble. This will save you from some typechecking and boxing, but will have a larger memory overhead.