tags:

views:

5679

answers:

4

I have a structure in C#.net. I have created an object of that structure. I need to cast this object of structure into ArrayList. I am using :

OrderMessageStructure.OrderMessage orderToModify = new OrderMessageStructure.OrderMessage();

object neworderobject = (object)orderToModify;
ArrayList arr = new ArrayList();
arr = (ArrayList)neworderobject;

But I am getting error "Unable to cast object of type 'OrderMessage' to type 'System.Collections.ArrayList'."

How to convert object/structure into ArrayList?

+3  A: 

You can't just cast any object into another object in C#. Its a type safe language.

You need to create an ArrayList and Add() your struct to it.

Better yet, create a List<StructType>() and add your struct to that.

CLR Via C#. Read it.


OrderMessageStructure.OrderMessage orderToModify = 
  new OrderMessageStructure.OrderMessage();

ArrayList arr = new ArrayList();
arr.Add(orderToModify);
Will
Better yet, use Generics. =]
strager
I did; the editor didn't escape my bracket for me. Just edited it.
Will
+1  A: 

You cannot convert these two objects because they have completely unrelated types. In order for a cast to succeed, OrderMessage must inherit from ArrayList which is almost certainly not what you want. It's more likely that you want to add an OrderMessage into an ArrayList which can be done like so.

ArrayList arr = new ArrayList();
arr.Add(orderToModify);
JaredPar
+1  A: 

No need to cast objects. Simply add them to your arraylist:

ArrayList list = new ArrayList();
list.Add(myObject);

but a better option is to use a generic List:

List<MyObject> list = new List<MyOjbect>();
list.Add(MyObject);

The advantage of the generic list is that it is strongly typed so you won't have to cast the object back to your type when pulling it out of your list.

Andrew Robinson
+1  A: 

Your question doesn't have quite enough information to give a sure answer.

If you want to make an ArrayList of OrderMessage objects then you need to create the arraylist FIRST and then ADD instances of OrderMessage.

If you want a strongly typed ArrayList of OrderMessage then use List from the Generic Namespace and ADD instances of OrderMessage to it.

If your OrderMessage has an array structure in it then you will need to add a method to it that returns an arraylist. You will have to write the code converting the OrderMessage to an ArrayList.

RS Conley