0

I'm having problems retrieving data from an ArrayList collection using C#. I'm saving a class into an ArrayList. The code works in saving the data, but I don't know how to write the code to retrieve it. I thought that _serviceList [0]._displayName would retrieve the first item, but it fails. How can I view all the items in the ArrayList?

Thanks.

class Service
{
  public string _displayName;
  public ServiceControllerStatus _status;

  public Service ()
  {
    _displayName = "";
    _status = ServiceControllerStatus.Stopped;
  }

  public Service (string displayName, ServiceControllerStatus status)
  {
    _displayName = displayName;
    _status = status;
  }
}

class Program
{
  public static ArrayList _serviceList = new ArrayList ();

  public Program ()
  {
    _serviceList = null;
  }

  static void Main (string [] args)
  {
    .
    .
    .

    _serviceList.Add (new Service (service.DisplayName, service.Status));
  }

  // The following code doesn't work.
  Console.WriteLine (_serviceList [0]._displayName);
3
  • I would avoid using ArrayList in C#, period. Instead, use a generic list of something you know the type of: List<Service> services = new List<Service>(); Commented Jun 26, 2014 at 19:25
  • You forgot to unbox element form the list ((type of your element)mylist[0]).somePropertyofTheElement="asdf"; Commented Jun 26, 2014 at 19:29
  • Thanks @VP. Your right that List is a better choice than ArrayList. :) Commented Jun 26, 2014 at 19:46

1 Answer 1

2

If you are working on .Net framework 2.0 or higher then use List<T> a generic , type safe version for List, and just changing the line

public static ArrayList _serviceList = new ArrayList ();

To

public static List<Service> _serviceList = new List<Service>();

would solve your issue.

But, if you are working on lower framework than 2.0 then you have to explicitly cast the object to Service like:

Console.WriteLine (((Service)_serviceList [0])._displayName);

since ArrayList would return it as of type object and not Service

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Habb. That did it. I can retrieve data using: foreach (var s in _serviceList) Console.Write (s._displayName);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.