0

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?

3
Contributors
3
Replies
21
Views
3 Years
Discussion Span
Last Post by ddanbe
1

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.

Edited by ddanbe: addition

Votes + Comments
cheers
0

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.

Edited by deceptikon

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.