I know that with Array Lists you can hold different types. Can you acomplish the same thing with arrays for example an array containing both ints and strings?

Recommended Answers

All 3 Replies

No, an array is defined for one type.
But you could do the following:

[StructLayout(LayoutKind.Explicit)]
    unsafe struct StringInt
    {
        [FieldOffset(0)]
        public fixed char name[30];
        [FieldOffset(0)]
        public int MyInt;
        //[FieldOffset(21)] etc.
        //possible other types       
    }

Do not forget to add: using System.Runtime.InteropServices;
Now you could make an array of StingInts.
This is called a variant record, like in Pascal.

commented: cheers +2

Can you acomplish the same thing with arrays for example an array containing both ints and strings?

Yes, actually you can. The reason ArrayList works with multiple types is that it technically holds type object, which is your highest level base class. You can create an array of object (ie. object[] foo;) for the same effect.

However, note that you'll experience the same problem as ArrayList. There's no static type checking, you must take care to cast appropriately on retrieval, and you can suffer the performance hit of boxing/unboxing. The generic List<> was introduced largely to correct those issues.

Oops, thought the OP was talking bout an Array, instead of ArrayList.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.