views:

65

answers:

3

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?

+2  A: 

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.

Kevin
Which would you recommend for maximum efficiency? I'm dealing with 50k element sized arays.
Soo
@Soo - Is it always 50k elements and is each of the 50k elements always filled?
Justin Niessner
always 50k, always filled
Soo
I would think, that if you are needing to resize the array, that the arraylist or List<Object> would be better. If there is no resizing necessary, then just use an object[], as that will be better for fast lookup than the List<Object> or ArrayList.
Richard J. Ross III
50k...The three pretty much do the same thing, in terms of storage, but honestly, I would probably reconsider using an array at all and try and use several smaller structures.
Kevin
Array is generally fastest, since it doesn't have the variable-length overhead of ArrayList and List.
KeithS
A: 

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.

KeithS
+2  A: 

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.

Albin Sunnanbo
^ is what you are describing here a structure?
Soo