Here I have:
Public Structure MyStruct
Public Name as String
Public Content as String
End Structure
Dim oStruct as MyStruct = New MyStruct()
oStruct.Name = ...
oStruct.Content = ...
Dim alList as ArrayList = new ArrayList()
alList.Add(oStruct)
I'd like to convert the ArrayList to a static strongly-typed Array of type MyStruct. How can I do that? I had no luck with ToArray.
I am using .NET Framework 2.0.
You have to cast the result of ToArray
MyStruct[] structs = (MyStruct[]) alList.ToArray(typeof(MyStruct));
I assume that since you are using ArrayList, you are using 1.1?
In which case, I suspect the following would work:
ArrayList list = new ArrayList();
MyStruct[] array = new MyStruct[list.Count];
list.CopyTo(array);
(edit - Bill's ToArray usage is more convenient - I didn't know about that one, but then, I very rarely [if ever] use ArrayList)
However, if MyStruct really is a struct, then I cannot say strongly enough that mutable structs are a bad idea - i.e. where you can set .Name and .Content after creation. Structs should almost always be immutable. In reality, your MyStruct looks like it should be a class. Also - I'm not "up" on VB, but are they public fields? Again - not recommended - properties would be preferable. I don't know about VB, but C# 3.0 has some very terse syntax for this:
public class SomeType
{
public string Name {get;set;}
public string Content {get;set;}
}
If you are using 2.0 or above, consider List<T> instead of ArrayList.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With