Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList Syntax

Tags:

c#

arraylist

So I need to use an ArrayList in C#. I looked it up in MSDN and they said I had to create a class, add System.Collections and Add

IList, ICollection, IEnumerable, 

ICloneable to the class

class clsExample : IList, ICollection, IEnumerable, ICloneable;

then I tried to use my Arraylist. So I typed:

ArrayList myAL = new ArrayList();

But the problem is that when I try to add things to the array (myAL.Add(1, Example);) the code doesn't find the array (myAL) and underlines an error to it. Am I missing something? Code:

    using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;

namespace WindowsFormsApplication7
{
    [SerializableAttribute]

    class clsAL : IList, ICollection, IEnumerable,
    ICloneable
    {
        ArrayList AL = new ArrayList();

    }
}
like image 493
OrangeWall Avatar asked Jan 19 '26 06:01

OrangeWall


1 Answers

To use ArrayList you do not need to implement the Interfaces you are having. Remove them and add the object in ArrayList in some method as given below. If it is possible you should look into generic list that saves you from type casting.

namespace WindowsFormsApplication7
{     
    class clsAL
    {
        ArrayList AL = new ArrayList();
        public void YourFun()
        {
             AL.Add("First");
        }
    }
}

Edit: You can look this msdn example for understand how to use ArrayList

using System;
using System.Collections;
public class SamplesArrayList  {

   public static void Main()  {

      // Creates and initializes a new ArrayList.
      ArrayList myAL = new ArrayList();
      myAL.Add("Hello");
      myAL.Add("World");
      myAL.Add("!");

      // Displays the properties and values of the ArrayList.
      Console.WriteLine( "myAL" );
      Console.WriteLine( "    Count:    {0}", myAL.Count );
      Console.WriteLine( "    Capacity: {0}", myAL.Capacity );
      Console.Write( "    Values:" );
      PrintValues( myAL );
   }

   public static void PrintValues( IEnumerable myList )  {
      foreach ( Object obj in myList )
         Console.Write( "   {0}", obj );
      Console.WriteLine();
   }

}
like image 89
Adil Avatar answered Jan 20 '26 18:01

Adil