How to convert an ArrayList to an array of structures in C#

1 Answer

0 votes
using System;
using System.Collections;

public struct MyStruct
{
    public int Id;
    public string Name;

    public MyStruct(int id, string name) {
        Id = id;
        Name = name;
    }
}

public class Program
{
    public static void Main()
    {
        ArrayList arrayList = new ArrayList();
        
        arrayList.Add(new MyStruct(1, "aaa"));
        arrayList.Add(new MyStruct(2, "bbb"));
        arrayList.Add(new MyStruct(3, "ccc"));
        arrayList.Add(new MyStruct(4, "ddd"));

        // Convert ArrayList to an array of structures
        MyStruct[] structArray = (MyStruct[])arrayList.ToArray(typeof(MyStruct));

        foreach (var item in structArray) {
            Console.WriteLine($"Id: {item.Id}, Name: {item.Name}");
        }
    }
}

  
/*
run:
  
Id: 1, Name: aaa
Id: 2, Name: bbb
Id: 3, Name: ccc
Id: 4, Name: ddd
  
*/

 



answered Feb 9, 2025 by avibootz

Related questions

1 answer 107 views
1 answer 185 views
185 views asked Jan 28, 2019 by avibootz
1 answer 169 views
169 views asked Sep 10, 2020 by avibootz
1 answer 161 views
2 answers 255 views
255 views asked Feb 9, 2017 by avibootz
...